Spring MVC 学习笔记 5《5.2 多文件上传》
接着上一篇,添加多文件支持
/ssm/src/main/java/com/jerry/ssm/controller/UpLoadController.java
和上图一样也在这个控制器里,只是这里分开列,方便查看
文件上传界面 http://localhost/goUploadFile.html
单文件上传接口 http://localhost/uploadFile
多文件上传接口 http://localhost/uploadFiles
。。。
/**
* 文件上传界面
* http://localhost/goUploadFile.html
* @throws JerryException
*/
@RequestMapping("/goUploadFile.html")
public String goUploadFile() throws JerryException {
return "goUploadFile";
}
/**
* 文件上传接口
* http://localhost/uploadFile
* @param model
* @return
*/
@ResponseBody
@RequestMapping(value="/uploadFile", produces={"application/json; charset=UTF-8"})
public Map<String, String> uploadFile(Integer refType, Long refId, String remark, @RequestParam("uploadfile") CommonsMultipartFile file, HttpServletRequest request) {
return uploadFile(refType, file, request);
}
/**
* 文件批量上传接口
* http://localhost/uploadFiles
* @param model
* @return
*/
@ResponseBody
@RequestMapping(value="/uploadFiles", produces={"application/json; charset=UTF-8"})
public Map<String, Object> uploadFiles(Integer refType, Long refId, String remark, @RequestParam("uploadfile") CommonsMultipartFile[] files, HttpServletRequest request) {
Map<String , Object> resultMap = new HashMap<String, Object>();
for (int i = 0; i < files.length; i++) {
resultMap.put("file"+(i+1) , uploadFile(refType, files[i], request));
}
return resultMap;
}
private Map<String, String> uploadFile(Integer refType, CommonsMultipartFile file, HttpServletRequest request) {
Map<String , String> resultMap = new HashMap<String ,String>();
// ============================ 存储文件到服务器硬盘 ============================
// --------------- 后端校验 开始 ---------------
if(file.isEmpty()){
resultMap.put("code", "1000");
resultMap.put("msg", "请选择上传文件");
return resultMap;
}
// 扩展名校验
String suffix = "";
try {
suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 从原文件名中截取出扩展名
} catch (Exception e) {
e.printStackTrace();
resultMap.put("code", "1001");
resultMap.put("msg", "扩展名错误");
return resultMap;
}
// --------------- 后端校验 结束 ---------------
// ------------ 生成文件名 ------------
// 图片类型_UUID_时间戳.扩展名
String fileName= refType + "_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + suffix;
// ------------ 确定保存位置 ------------
// 从配置文件读取绝对路径
String diskPath = "file" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date());
// 用于展示的url虚拟路径
String urlPath = diskPath.replace("\\", "/");
// 生成保存路径
File filePath = new File(PropertiesUtils.get("upload_path) + diskPath);
if(!filePath.exists()){// 如果不存在就创建
try {
filePath.mkdirs();
} catch (Exception e) {
e.printStackTrace();
resultMap.put("code", "2001");
resultMap.put("msg", "创建保存路径失败");
return resultMap;
}
}
// ------------ 保存文件 ------------
try {
// filePath + fileName = 完整文件路径
//file.transferTo(new File(filePath, fileName));
// 保存上传的文件到硬盘
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath, fileName));
} catch (Exception e) {
e.printStackTrace();
resultMap.put("code", "4001");
resultMap.put("msg", "文件保存失败");
return resultMap;
}
//将上传记录存储到数据库记录表中(用户ID,上传文件原始名,上传文件新名,时间,文件类型)
int i = 1; // 保存文件信息到数据库,返回成功标识(这一步本Demo就省了);
// 返回结果给客户端
if(i > 0){
resultMap.put("code", "1000");
resultMap.put("msg", "文件上传成功");
resultMap.put("fileName", file.getOriginalFilename());
resultMap.put("url", urlPath + "/" + fileName);
resultMap.put("fullUrl", request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ "/" + urlPath + "/" + fileName);
}else{
resultMap.put("code", "4000");
resultMap.put("msg", "文件上传失败");
}
return resultMap;
}
添加JSP 文件上传界面
/ssm/src/main/webapp/WEB-INF/jsp/goUploadFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>SpringMVC 文件上传 Demo</title>
</head>
<body>
<h1>SpringMVC 单文件上传 Demo</h1>
<form action="uploadFile" method="post" enctype="multipart/form-data">
文件归属对象类型:<input type="text" name="refType" value=""/><br />
文件归属对象id:<input type="text" name="refId" value=""/><br />
文件描述:<input type="text" name="remark" value=""/><br />
文件:<input type="file" name="uploadfile" /><br />
<input type="submit" value="点击上传" />
</form>
<h1>SpringMVC 多文件上传 Demo</h1>
<form action="uploadFiles" method="post" enctype="multipart/form-data">
文件归属对象类型:<input type="text" name="refType" value=""/><br />
文件归属对象id:<input type="text" name="refId" value=""/><br />
文件描述:<input type="text" name="remark" value=""/><br />
文件1:<input type="file" name="uploadfile" /><br />
文件2:<input type="file" name="uploadfile" /><br />
文件3:<input type="file" name="uploadfile" /><br />
<input type="submit" value="批量上传" />
</form>
</body>
</html>
甩锅说明
实现多文件的关键是 CommonsMultipartFile[] files
但是我暴力的用for
遍历单个上传函数的方式,肯定是有待优化的。