實現多文件上傳CommonsMultipartResolver前端
注意:接口使用DefaultMultipartHttpServletRequest接收(前端ajaxsubmit提交表單)若使用他們則表單必需要有文件上傳不然會報錯!web
2018年05月23日 18:01:21ajax
一、在spring配置文件中配置文件上傳解析器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>
++++++接口使用++++++++++++++++++服務器
- @Controller
- 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";
- }
- }