今天一个新来的同事要写批量上传图片的接口,但是他没做过文件上传,我就想到前端时间自己做过pdf文件的上传,碰巧我自己手头上功能已经做完,他又毫无头绪,就自己试了一下,在自己之前做的上传pdf文件上进行修改成批量上传图片,这个对批量上传任何文件都适用。
1.在springMVC.xml的配置文件添加multipartResolver
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
2.在Controller层写上代码:
// 批量上传文件
@RequestMapping("/uploadPicture")
public @ResponseBody ResultObject uploadPicture(@RequestParam MultipartFile[] files, HttpServletRequest request, int id)
throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
String res = sdf.format(new Date());
ResultObject retObj = ResultObject.getFailResultObject();
Map<String, Object> model = new HashMap<String, Object>(2);
int flag = 0;
String msg = "上传失败";
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("WEB-INF/upload");
// 创建年月文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
// 原始名称
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
// 获取文件名
String fileName = file.getOriginalFilename();
System.out.println(fileName);
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + fileName);
// 判断目标文件所在目录是否存在
if (!newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
// 将内存中的数据写入磁盘
file.transferTo(newFile);
// 完整的url
String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + fileName;
System.out.println("fileUrl:" + fileUrl);
msg = "上传成功";
}
model.put("flag", flag);
model.put("msg", msg);
retObj.setData(model);
return retObj;
}
3.编写一个html文件测试:
<html>
<head>
<meta charset="UTF-8">
<title>file upload</title>
</head>
<body>
<form action="http://localhost:8080/项目名/controller路径/uploadPicture" method="post" enctype="multipart/form-data">
<span>用户名</span> <input type="text" name="name"/><br/>
<span>文 件1</span> <input type="file" name="files"/><br/>
<span>文 件2</span> <input type="file" name="files"/><br/>
<span>文 件3</span> <input type="file" name="files"/><br/>
<input type="submit" value="提交">
</form>
</body>
</html>