Spring MVC 实现文件上传与下载
1、spring-mvc.xml配置:
<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
2 、引入相关jar包:commons-fileupload.jar、commons-io-1.4.jar和spring相关jar包
3 表单属性为:enctype="multipart/form-data"
4、实现代码
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传实体类
* @author ***
* 这里不将图片信息存入数据库
*/
public class FileUpload {
private String id;
private String fileName;
private String filePath;
private MultipartFile csvFile;
// getter方法和setter方法省略
}
/**
* 文件上传下载控制层
* @author ***
*/
@Controller
@RequestMapping("/fileController")
public class FileController {
/**
* 文件上传
* @author ***
*/
@RequestMapping("/upload")
@ResponseBody
public Json upload(FileUpload file, HttpServletRequest request) {
Json json = new Json();
try {
FileUploadUtil.uploadFile(file.getCsvFile(), request);
String fileName = file.getCsvFile().getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));
if (".csv".indexOf(suffix.toLowerCase()) != -1) {
json.setSuccess(true);
json.setMsg("文件上传成功。");
} else {
json.setSuccess(false);
json.setMsg("上传的文件格式不支持!");
}
} catch (Exception e) {
json.setMsg(e.getMessage());
}
return json;
}
/**
* 文件下载
* @author ***
*/
@RequestMapping("/download")
public void download(HttpServletRequest request,HttpServletResponse response) {
String fileName = "部门管理.xls";
String filePath = request.getSession().getServletContext()
.getRealPath("/") + "\\download" + fileName ;
try {
FileDownloadUtil.modelDownload(fileName, filePath, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import com.common.model.FileUpload;
/**
* 文件上传通用类
* @author ***
*/
public class FileUploadUtil {
public static void uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
if (!file.isEmpty() && file.getSize() > 0) {
try {
String fileName = file.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));// 后缀名
String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + dateTime() + suffix;
if ((".csv".indexOf(suffix.toLowerCase()) != -1)) {
byte[] bytes = file.getBytes();
Integer fileSize = (int) file.getSize() / 1024;
if (fileSize <= 10240) {
File dir = new File(request.getSession().getServletContext().getRealPath("/upload"));
if (!dir.exists()) {
dir.mkdirs();
}
File filePath = new File(request.getSession().getServletContext().getRealPath("/upload") + newFileName));
FileCopyUtils.copy(bytes, filePath);
} else {
throw new RuntimeException("上传的文件太大,文件大小不能超过10M!");
}
} else {
throw new RuntimeException("上传的文件格式不支持!");
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}
// 获得文件路径,包含到文件名
public static String getFilePath(FileUpload file, HttpServletRequest request) {
String fileName = file.getCsvFile().getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf("."));// 后缀名
String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_" + dateTime() + suffix;
File filePath = new File(request.getSession().getServletContext().getRealPath(ConfigUtil.getUploadbundle().getString("csvFilePath") + newFileName));
return filePath.toString();
}
// 获取时间
public static String dateTime() {
DateFormat df = new SimpleDateFormat("yyyyMMdd_HHmm");
String date = df.format(new Date());
return date;
}
}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class FileDownloadUtil {
/**
* <p>文件下载工具方法</p>
* @param fileName
* @param downloadPath
* @param response
* @throws Exception
*/
public static void modelDownload(String fileName, String downloadPath, HttpServletResponse response) throws Exception{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
long fileLength = new File(downloadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downloadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[1024];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null){
bis.close();
}
if (bos != null){
bos.close();
}
}
}
}
Jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<include page="../../style_js.jsp"></include> <!-- 引入相关css文件个js脚本 -->
<script type="text/javascript">
$(function(){
parent.$.messager.progress('close');
$('#form').form({
url: '${pageContext.request.contextPath}/fileController/upload',
onSubmit : function() {
parent.$.messager.progress({
title : '提示',
text : '数据处理中,请稍后....'
});
},
success : function(result) {
result = $.parseJSON(result);
if (result.success) {
parent.$.modalDialog.openner_dataGrid.datagrid('reload');
parent.$.messager.alert('提示', result.msg, 'info');
parent.$.modalDialog.handler.dialog('close');
parent.$.messager.progress('close');
} else {
parent.$.messager.alert('提示', result.msg, 'info');
parent.$.messager.progress('close');
}
}
});
});
</script>
<div class="easyui-layout" data-options="fit:true,border:false">
<div data-options="region:'center',border:false" title="">
<form id="form" method="post" enctype="multipart/form-data">
<table class="">
<tr>
<td><b>请选择上传文件:</b><input type="file" id="csvFile" name="csvFile" class=""/></td>
</tr>
<tr>
<td><a href="${pageContext.request.contextPath}/fileController/download">模板文件下载</a></td>
</tr>
</table>
</form>
</div>
</div>