SpringMvc檔案上傳

lonecloud發表於2016-10-23

在Spring-mvc.xml注入bean

 1     <!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 -->
 2     <bean id="multipartResolver"
 3         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 4         <!-- 預設編碼 -->
 5         <property name="defaultEncoding" value="utf-8" />
 6         <!-- 檔案大小最大值 -->
 7         <property name="maxUploadSize" value="10485760000" />
 8         <!-- 記憶體中的最大值 -->
 9         <property name="maxInMemorySize" value="40960" />
10     </bean>

如果想要在model裡面進行檔案上傳到資料庫中則

 1 package cn.lonecloud.model;
 2 
 3 import java.io.Serializable;
 4 import java.util.List;
 5 
 6 import org.springframework.web.multipart.MultipartFile;
 7 
 8 public class Test implements Serializable{
 9 
10     private String id;
11     
12     private String name;
13     
14     private String price;
15     //檔案上傳List
16     private List<MultipartFile> files;
17 
18     public String getId() {
19         return id;
20     }
21 
22     public void setId(String id) {
23         this.id = id;
24     }
25 
26     public String getName() {
27         return name;
28     }
29 
30     public void setName(String name) {
31         this.name = name;
32     }
33 
34     public String getPrice() {
35         return price;
36     }
37 
38     public void setPrice(String price) {
39         this.price = price;
40     }
41 
42     public List<MultipartFile> getFiles() {
43         return files;
44     }
45 
46     public void setFiles(List<MultipartFile> files) {
47         this.files = files;
48     }
49     
50     
51 }

Controller層程式碼

 1     /**
 2      * 將檔案封裝在Model裡面
 3      * @Description: 
 4      * @param request 用來獲取路徑
 5      * @param test 封裝類
 6      * @param model 返回模型
 7      * @return
 8      */
 9     @RequestMapping("save")
10     public String saveTest(HttpServletRequest request,
11             @ModelAttribute Test test, Model model) {
12         List<MultipartFile> files = test.getFiles();//獲取檔案
13         List<String> fileNames = new ArrayList<>();
14         if (null != files && files.size() != 0) {//判斷空
15             for (MultipartFile multipartFile : files) {
16                 String fileName = multipartFile.getOriginalFilename();
17                 String realPath = request.getServletContext().getRealPath(
18                         "/file");//獲取路徑
19                 fileNames.add(fileName);
20                 File parents = new File(realPath);
21                 if (!parents.exists()) {
22                     parents.mkdirs();
23                 }
24                 File destFile = new File(parents, fileName);
25                 try {
26                     multipartFile.transferTo(destFile);//拷貝檔案
27                 } catch (IllegalStateException e) {
28                     // TODO Auto-generated catch block
29                     e.printStackTrace();
30                 } catch (IOException e) {
31                     // TODO Auto-generated catch block
32                     e.printStackTrace();
33                 }
34             }
35         }
36         model.addAttribute("test", test);
37         return "fileUpload/details";
38     }

直接暴露在控制層當做引數使用

 1     /**
 2      * 直接檔案獲取
 3      * @Description: 
 4      * @param request
 5      * @param files
 6      * @param result
 7      * @return
 8      */
 9     @RequestMapping("/saveFile")
10     public String saveFile(@RequestParam("files") List<MultipartFile> files,HttpServletRequest request) {
11 //        public String saveFile(@RequestParam("files") CommonsMultipartFile[] files,HttpServletRequest request) {
12         List<String> fileNames = new ArrayList<>();
13         System.out.println(files);
14         
15         if (null != files && files.size() != 0) {
16 //        if (null != files && files.length != 0) {
17             for (MultipartFile multipartFile : files) {
18                 String fileName = multipartFile.getOriginalFilename();
19                 String realPath = request.getServletContext().getRealPath(
20                         "/file");
21                 fileNames.add(fileName);
22                 File parents = new File(realPath);
23                 if (!parents.exists()) {
24                     parents.mkdirs();
25                 }
26                 File destFile = new File(parents, fileName);
27                 try {
28                     multipartFile.transferTo(destFile);
29                 } catch (IllegalStateException e) {
30                     // TODO Auto-generated catch block
31                     e.printStackTrace();
32                 } catch (IOException e) {
33                     // TODO Auto-generated catch block
34                     e.printStackTrace();
35                 }
36             }
37         }
38         return "fileUpload/details";
39     }

 uploadFile.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form:form action="save" enctype="multipart/form-data" method="post" commandName="test">
        select a file<input type="file" name="files" multiple><!-- 單檔案上傳 --><br>
        select files<!-- <input type="file" name="files" multiple> --><!-- 多檔案上傳 --><br>
        <input type="submit" value="上傳">
    </form:form>
</body>
</html>

 

相關文章