实现多文件上传CommonsMultipartResolver
注意:接口使用DefaultMultipartHttpServletRequest接收(前端ajaxsubmit提交表单)若使用他们则表单必须要有文件上传否则会报错!
2018年05月23日 18:01:21
1、在spring配置文件中配置文件上传解析器
- <!-- 文件上传解析器 -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="utf-8"></property>
- <property name="maxUploadSize" value="10485760000"></property><!-- 最大上传文件大小 -->
- <property name="maxInMemorySize" value="10960"></property>
- </bean>
++++++接口使用++++++++++++++++++
- public class FileController{
- @RequestMapping("/fileUpload.do")
- public String fileUpload(HttpServletRequest request,HttpServletResponse response){
- long startTime=System.currentTimeMillis(); //获取开始时间
- CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
- if(multipartResolver.isMultipart(request)){ //判断request是否有文件上传
- MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
- Iterator<String> ite = multiRequest.getFileNames();
- while(ite.hasNext()){
- MultipartFile file = multiRequest.getFile(ite.next());
- if(file!=null){
- File localFile = new File("D:/"+file.getOriginalFilename());
- try {
- file.transferTo(localFile); //将上传文件写到服务器上指定的文件
- } catch (IllegalStateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- long endTime=System.currentTimeMillis(); //获取结束时间
- System.out.println("上传文件共使用时间:"+(endTime-startTime));
- return "success";
- }
- }