关于ssm框架整合文件的上传和下载.
首先来看单个附件的上传和下载:
1.首先创建一个用来测试的jsp文件上传下载的页面 代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传下载</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/file/upload.chao"
method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file" width="120px"> <input
type="submit" value="上传">
</form>
<hr>
<form action="${pageContext.request.contextPath }/file/down.chao"
method="get">
<input type="submit" value="下载">
</form>
</body>
</html>
2.在自己已经构建好的maven web项目中 pom.xml配置文件中添加上传下载所需要的jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
3.在spring的applicationContext.xml配置文件中添加文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="5242440"></property>
</bean>
4.在controller层实现上传下载的代码
package com.chao.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
/**
* 下载 测试
* @author 王一土
*
*/
@Controller
@RequestMapping("file")
public class UoloadController {
@RequestMapping(value="/upload",method=RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File dir = new File(path,fileName);
if(!dir.exists()){
dir.mkdirs();
}
file.transferTo(dir);
return fileName;
}
@RequestMapping("/down")
public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{
String fileName = request.getSession().getServletContext().getRealPath("upload")+"/101.jpg";
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
String filename = "下载文件.jpg";
filename = URLEncoder.encode(filename,"UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
}
}
多个附件上传并将附件保存在Oracle数据库Blob字段:
注意:首先:Form表单中的file文件标签使用相同的名称。
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'file_upload_test.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function addline(){
newline = document.all.test.insertRow();
newline.insertCell().innerHTML="<input type='file' name=file size='60'> "+"<button onclick='javascript:removeline(this)'>移除</button>";
}
function removeline(obj){
var objSourceRow=obj.parentNode.parentNode;
var objTable=obj.parentNode.parentNode.parentNode.parentNode;
objTable.lastChild.removeChild(objSourceRow);
}
</script>
</head>
<body>
<form name="theform" method="post" action="fileUploadTest" enctype="multipart/form-data">
<h4>附件上传:</h4>
<table id=test border="0">
<tr>
<td>
<input type="file" name="file" size="60">
</td>
</tr>
</table>
<button onclick="addline();">单击此处添加更多附件</button><hr>
<input type="submit" />
</form>
</body>
</html>
文件上传的同时,传其他参数:
首先我们需要知道,http get请求是可以有body的,post请求也是可以在url上增加参数以get方式提交参数。所以,我们把文件以post方式提交,其他参数以get方式提交,而Controller的请求方式设为POST即可。代码如下:
@ResponseBody
@RequestMapping(value="/SQHDfileup",method = RequestMethod.POST,produces = "text/json;charset=utf-8")
//参数中的files要和页面中input输入框的name值相同
public void uploadResource(@RequestParam MultipartFile[] files,@RequestParam("RW_BH") String RW_BH,HttpServletRequest request,HttpServletResponse response) throws IOException, FileUploadException, SQLException {
}
思考,此处的file也是通过@RequestParam接受的,可以使用@RequestBody接受吗?可以不加注解吗(不加注解应该是默认get,且要求名字一致)?
其次:无法直接向Blob字段insert数据,需要先插入空,然后必须SELECT得到BLOB的对象再向里写。
package com.inspur.ahDqyJMS.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oracle.sql.BLOB;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.inspur.ahyhgl.util.ClientOutput;
import com.inspur.service.GETuuid;
import weblogic.jdbc.vendor.oracle.OracleThinBlob;
/**多文件上传附件税企互动*/
@Controller
public class UpLoadController {
private static Logger logger = LoggerFactory.getLogger(UpLoadController.class);
// 192.168.0.X是本机地址(要改成自己的IP地址),1521端口号,XE是精简版Oracle的默认数据库名
private static String USERNAMR = "xxxxx";
private static String PASSWORD = "xxxxx";
private static String DRVIER = "oracle.jdbc.OracleDriver";
private static String URL = "jdbc:oracle:thin:@xx.xxx.xxx.xxx:1521:orcl";
// 创建一个数据库连接
Connection conn = null;
// 创建预编译语句对象,一般都是用这个而不用Statement
PreparedStatement pstm = null;
// 创建一个结果集对象
ResultSet rs = null;
@ResponseBody
@RequestMapping(value="/SQHDfileup",method = RequestMethod.POST,produces = "text/json;charset=utf-8")
//参数中的files要和页面中input输入框的name值相同
public void uploadResource(@RequestParam MultipartFile[] files,@RequestParam("RW_BH") String RW_BH,HttpServletRequest request,HttpServletResponse response) throws IOException, FileUploadException, SQLException {
/*public void uploadResource(HttpServletRequest request,HttpServletResponse response) throws IOException, FileUploadException, SQLException {
*/
String fhString = "";
/**********************************第一部分修改*********************************/
/*
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//List<MultipartFile> fileList = multipartRequest.getFiles("file");
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
if(fileMap == null || fileMap.size() == 0){
logger.error("请上传文件,注意文件的name属性为file");
}
Collection<MultipartFile> files = fileMap.values();
String path = "D:\\1111\\";
System.out.println(path);
StringBuffer stringBuffer=new StringBuffer();
for (MultipartFile multipartFile : files) {
if(!multipartFile.isEmpty()) {
//将多个文件名拼接在一个字符串中,用;分隔
stringBuffer.append(multipartFile.getOriginalFilename());
stringBuffer.append(";");
File dir=new File(path, multipartFile.getOriginalFilename());
if(!dir.exists()) {
dir.mkdirs();
}
multipartFile.transferTo(dir);
}
}
//去除最后一个;号
String filePath=stringBuffer.substring(0, stringBuffer.length()-1);//上传附件文件名拼接字符串
*/
/***********************************第一部分***********************************/
//获取文件上传路径;将附件保存至系统某个目录下
//String path = request.getSession().getServletContext().getRealPath("upload");
String path = "/csopt/opt/workspace/upload";
System.out.println(path);
StringBuffer stringBuffer=new StringBuffer();
for (MultipartFile multipartFile : files) {
if(!multipartFile.isEmpty()) {
//将多个文件名拼接在一个字符串中,用;分隔
stringBuffer.append(multipartFile.getOriginalFilename());
stringBuffer.append(";");
File dir=new File(path, multipartFile.getOriginalFilename());
if(!dir.exists()) {
dir.mkdirs();
}
multipartFile.transferTo(dir);
}
}
//去除最后一个;号
String filePath=stringBuffer.substring(0, stringBuffer.length()-1);//上传附件文件名拼接字符串
/***********************************第二部分***********************************/
/****自己测试****/
/*String path = "D:\\1111\\";
String filePath ="111.jpg";*/
/****自己测试****/
String[] files1 = filePath.split(";");
for(String fp : files1){
conn = getConnection();
conn.setAutoCommit(false);//程序必须调用commit或者rollback方法
// 初始化驱动包,这里我用的事oracle,jdbc是基础,都一样的
String uuid = UUID.randomUUID().toString();//生成一个uuid
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String scsj = df.format(new Date());// new Date()为获取当前系统时间
String sql = "insert into SQHD_FJ (ID,BLOBVALUE,FILENAME,SCSJ) values ('"+RW_BH+ "',empty_blob(),'"+fp+"','"+scsj+"')";//先插入空的blob值empty_blob
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement("select blobvalue from SQHD_FJ where id= '"+ RW_BH + "' for update");
ResultSet rset = pstmt.executeQuery();
File f = new File(path + "/" +fp);
logger.error("Upload Path"+path + "/" +fp);
InputStream fin = new FileInputStream(f);
if (rset.next()){
try{
BLOB oracleblob = (oracle.sql.BLOB) rset.getBlob(1);
OutputStream out = oracleblob.getBinaryOutputStream();
BufferedOutputStream output = new BufferedOutputStream(out);
BufferedInputStream input = new BufferedInputStream(fin);
byte[] buff = new byte[2048]; //用做文件写入的缓冲
int bytesRead;
while(-1 != (bytesRead = input.read(buff, 0, buff.length))){
output.write(buff, 0, bytesRead);
}
fin.close();
out.flush();
output.close();
fhString = "{\"UUID\": \"\",\"MESSAGE\": \"[附件上传成功]\",\"FLAG\": \"1\"}";
}catch(Exception e){
fhString = "{\"UUID\": \"\",\"MESSAGE\": \"[附件上传失败]\",\"FLAG\": \"0\"}";
}finally{
pstmt.executeUpdate();//修改
pstmt.close();
conn.commit();
conn.close();
f.delete();//最后别忘了删除临时文件
}
}
}
ClientOutput.doResponseJsonStr(response,fhString);
}
/**
* 获取Connection对象
*
* @return
*/
public Connection getConnection() {
try {
Class.forName(DRVIER);
conn = DriverManager.getConnection(URL, USERNAMR, PASSWORD);
System.out.println("成功连接数据库");
} catch (ClassNotFoundException e) {
throw new RuntimeException("class not find !", e);
} catch (SQLException e) {
throw new RuntimeException("get connection error!", e);
}
return conn;
}
/**
* 释放资源
*/
public void releaseResource() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}