1. 程式人生 > 實用技巧 >SpringMVC(4):檔案上傳與下載

SpringMVC(4):檔案上傳與下載

一,檔案上傳

檔案上傳是專案開發中最常見的功能之一 ,springMVC 可以很好的支援檔案上傳,但是SpringMVC上下文中預設沒有裝配MultipartResolver,因此預設情況下其不能處理檔案上傳工作

如果想使用Spring的檔案上傳功能,則需要在上下文中配置MultipartResolver

第一步:檔案配置及導包

對springmvc-servlet.xml進行檔案配置

1 <!--檔案上傳配置-->
2     <bean id="multipartResolver"
3           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4
<property name="defaultEncoding" value="utf-8"/> 5 <!-- 上傳檔案大小上限,單位為位元組(10485760=10M) --> 6 <property name="maxUploadSize" value="1048576"/> 7 <property name="maxInMemorySize" value="40960"/> 8 </bean>

第二步:前端 upload.jsp

為了能上傳檔案,必須將表單的method設定為post,並將enctype設定為multipart/form-data;只有在這樣的情況下,瀏覽器才會把使用者選擇的檔案以二進位制資料傳送給伺服器

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <body>
 4 
 5 <form action="${pageContext.request.contextPath}/upload1" 
 6                enctype="multipart/form-data" method="post">
 7     <p> 上傳 檔案:<input type="file" name="file"/></p>
 8
<p><input type="submit" value="上傳"></p> 9 </form> 10 11 </body> 12 </html>

方式1:採用流的方式上傳檔案

@RequestParam(" file ") 將name = file控制元件得到的檔案封裝成CommonsMultipartFile物件;批量上傳CommonsMultipartFile則為陣列即可

CommonsMultipartFile的常用方法:

  • String getOriginalFilename():獲取上傳檔案的原名
  • InputStream getInputStream():獲取檔案流
  • void transferTo(File dest):將上傳檔案儲存到一個目錄檔案中

程式碼

 1 @Controller
 2 public class ControllerUpload {
 3 
 4     @RequestMapping("/upload1")
 5     public String fileUpload(@RequestParam("file") CommonsMultipartFile file,
 6                                          HttpServletRequest request) throws IOException {
 7 
 8         //1.獲取檔名字
 9         String uploadName = file.getOriginalFilename();
10         //2.如果檔名為空則返回首頁
11         if ("".equals(uploadName)) {
12             return "redirect:/index.jsp";
13         }
14         System.out.println("上傳的檔名:" + uploadName);
15 
16         //3.上傳路徑儲存設定
17         String path = request.getServletContext().getRealPath("/WEB-INF/upload1");
18         //4.如果路徑不存在就建立一個
19         File realPath = new File(path);
20         if (!realPath.exists()) {
21             realPath.mkdir();
22         }
23         System.out.println("儲存的路徑名:" + realPath);
24 
25         //5.檔案輸入流
26         InputStream in = file.getInputStream();
27         //6.檔案輸入流
28         FileOutputStream out = new FileOutputStream(new File(realPath, uploadName));
29 
30         //7.讀取
31         int len = 0;
32         byte[] bytes = new byte[1024];
33         while ((len = in.read(bytes)) != -1) {
34             out.write(bytes, 0, len);
35             out.flush();
36         }
37         out.close();
38         in.close();
39 
40         return "redirect:/success.jsp";
41     }
42 }

執行測試

儲存的位置

方式2:採用file.Transto 來上傳

 1 @Controller
 2 public class ControllerUpload {
 3 
 4     @RequestMapping("/upload2")
 5     public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, 
 6                                        HttpServletRequest request) throws IOException {
 7 
 8         //上傳路徑儲存設定
 9         String path = request.getServletContext().getRealPath("/WEB-INF/upload2");
10         File realPath = new File(path);
11         if (!realPath.exists()) {
12             realPath.mkdir();
13         }
14 
15         //上傳檔案地址
16         System.out.println("上傳檔案儲存地址:" + realPath);
17 
18         //通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
19         file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
20 
21         return "redirect:/success.jsp";
22     }
23 }

【注意點:這裡我們有兩種方式顯示上傳成功的介面,第一種就是像我一樣新建一個成功的success .jsp;

然後上傳成功後讓它重定向到成功介面。第二種就是執行JSON,在controller中加上@ResponseBody,並且return一句話,這樣上傳成功後就會直接顯示出你return的話】

二,檔案下載

第一步:前端 download.jsp

1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html>
3 <body>
4 
5 <a href="${pageContext.request.contextPath}/download">下載圖片</a>
6 
7 </body>
8 </html>

第二步:controller程式碼

  1. 設定 response 響應頭
  2. 讀取檔案 -- InputStream
  3. 寫出檔案 -- OutputStream
  4. 執行操作
  5. 關閉流 (先開後關)

程式碼

 1 @Controller
 2 public class ControllerDownload {
 3 
 4     @RequestMapping("/download")
 5     public String downloads(HttpServletResponse response) throws Exception{
 6 
 7         //1.要下載的圖片地址
 8         String path="F:\\圖片";
 9         String  fileName = "9.jpg";
10 
11         //2.設定response 響應頭
12         response.reset(); //設定頁面不快取,清空buffer
13         response.setCharacterEncoding("UTF-8"); //字元編碼
14         response.setContentType("multipart/form-data"); //二進位制傳輸資料
15         //3.設定響應頭
16         response.setHeader("Content-Disposition",
17                 "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
18 
19         File file = new File(path,fileName);
20         //4.讀取檔案--輸入流
21         InputStream input=new FileInputStream(file);
22         //5.寫出檔案--輸出流
23         OutputStream out = response.getOutputStream();
24 
25         byte[] buff =new byte[1024];
26         int index=0;
27         //6.執行 寫出操作
28         while((index= input.read(buff))!= -1){
29             out.write(buff, 0, index);
30             out.flush();
31         }
32         out.close();
33         input.close();
34         return null;
35     }
36 }

執行測試