一、form表单属性中加上enctype="multipart/form-data"
form表单的
二、配置文件中配置MultipartResolver
文件超出限制会在进入controller前抛出异常,在允许范围内这个配置无影响
三、MultipartFile
接受文件并通过IO二进制流(MultipartFile.getInputStream())输入到FileOutStream保存文件,然后该干嘛就干嘛
参数接收同MultipartFile 接收一样。
接受form表单截图中name为file和id的文件和参数。如下
@RequestMapping(value = "attendee_uploadExcel.do")
@ResponseBody
public void uploadExcel(@RequestParam("file")
MultipartFile file, @RequestParam("id")
String id) throws Exception {
//form表单提交的参数测试为String类型
if (file == null) return ;
String fileName = file.getOriginalFilename();
String path =
getRequest().getServletContext().getRealPath("/upload/excel");
//获取指定文件或文件夹在工程中真实路径,getRequest()这个方法是返回一个HttpServletRequest,封装这个方法为了处理编码问题
FileOutputStream fos =
FileUtils.openOutputStream(new
File(path+"/"
+fileName));//打开FileOutStrean流
IOUtils.copy(file.getInputStream(),fos);//将MultipartFile file转成二进制流并输入到FileOutStrean
fos.close();//
......
}
四、servlet上传文件。HttpServletRequest
req强转成MultipartHttpServletRequest
req后,req.getParameter("id");
HttpServletRequest request;
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
MultipartFile file
= multipartRequest.getFile("file");
String id = multipartRequest.getParameter("id");
String fileName = file.getOriginalFilename();
五、maven配置
添加maven依赖:
commons-fileupload
commons-fileupload
1.2.2
Spring注解配置:
@Bean
public MultipartResolver multipartResolver() throws IOException
{
CommonsMultipartResolvercommonsMultipartResolver=new CommonsMultipartResolver();
commonsMultipartResolver.setUploadTempDir(new
FileSystemResource("fileUpload/temp"));//上传中临时文件存放目录
commonsMultipartResolver.setMaxUploadSize(2097152);//上传文件的总大小限制,这里设置为2G
commonsMultipartResolver.setDefaultEncoding("UTF-8");//编码
//commonsMultipartResolver.setResolveLazily();//延迟解析,解析文件的时候再抛异常
//commonsMultipartResolver.setServletContext();
commonsMultipartResolver.setMaxInMemorySize(1024);//缓存大小限制
//commonsMultipartResolver.setMaxUploadSizePerFile();//单个文件大小限制
//commonsMultipartResolver.setPreserveFilename();
return
commonsMultipartResolver;
}