1. 程式人生 > >SpringMVC文件上傳和下載的實現

SpringMVC文件上傳和下載的實現

文件的上傳 transfer AR handle LV ont href gif position

SpringMVC通過MultipartResolver(多部件解析器)對象實現對文件上傳的支持。

MultipartResolver是一個接口對象,需要通過它的實現類CommonsMultipartResolver來完成文件的上傳工作。

1.使用MultipartResolver對象,在XML中配置Bean.

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4
xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-4.3.xsd">
9 <context:annotation-config/> 10 <context:component-scan base-package="com.wxy.controller"/> 11 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 12 <property name="prefix" value="/WEB-INF/jsp/"></property> 13
<property name="suffix" value=".jsp"></property> 14 </bean> 15 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 16 <property name="defaultEncoding" value="UTF-8" /> 17 <property name="maxUploadSize" value="2097152" /> 18 </bean> 19 </beans>

2.fileUpload.jsp上傳頁面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>文件上傳</title>
 5     <script>
 6         <%--判斷是否填寫上傳人並已經選擇上傳文件--%>
 7         function check() {
 8             var name = document.getElementById("name").value();
 9             var name = document.getElementById("file").value();
10             if(name==""){
11                 alert("請填寫上傳人");
12                 return false;
13             }
14             if(file.length==0||file==""){
15                 alert("請選擇上傳文件");
16                 return false;
17             }
18             return true;
19         }
20     </script>
21 </head>
22 <body>
23 <%--enctype="multipart/form-data"采用二進制流處理表單數據--%>
24 <form action="${pageContext.request.contextPath}/fileUpload.action" method="post" enctype="multipart/form-data" onsubmit="return check()">
25     上傳人:<input id="name" type="text" name="name"/><br/>
26     請選擇文件:<input id="file" type="file" name="uploadfile" multiple="multiple"/><br/>
27     <%--multiple屬性選擇多個文件上傳--%>
28     <input type="submit" value="文件上傳" />
29 </form>
30 </body>
31 </html>

3.fileDownload.jsp下載頁面

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
 2 <%@ page import="java.net.URLEncoder" %>
 3 <html>
 4 <head>
 5     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 6     <title>文件下載</title>
 7 </head>
 8 <body>
 9 <a href="${pageContext.request.contextPath}/download.action?filename=<%=URLEncoder.encode("圖像.txt","UTF-8")%>">文件下載</a>
10 </body>
11 </html>

4.FileUploadAndDownloadController.java文件上傳和下載控制器類

技術分享圖片
 1 package com.wxy.controller;
 2 
 3 import org.apache.commons.io.FileUtils;
 4 import org.springframework.http.HttpHeaders;
 5 import org.springframework.http.HttpStatus;
 6 import org.springframework.http.MediaType;
 7 import org.springframework.http.ResponseEntity;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RequestParam;
11 import org.springframework.web.multipart.MultipartFile;
12 
13 import javax.servlet.http.HttpServletRequest;
14 import java.io.File;
15 import java.net.URLEncoder;
16 import java.util.List;
17 import java.util.UUID;
18 
19 @Controller("controller")
20 public class FileUploadAndDownloadController {
21     @RequestMapping("/tofileUpload")
22     public String toupload(){
23         return "fileUpload";
24     }
25     @RequestMapping("/tofiledownload")
26     public String todownload(){
27         return "download";
28     }
29     @RequestMapping("/fileUpload.action")
30     public String handleFormUpload(@RequestParam("name") String name,
31                                    @RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) {
32         if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
33             for (MultipartFile file : uploadfile) {
34                 String originalFilename = file.getOriginalFilename();
35                 String dirPath = request.getServletContext().getRealPath("/upload/");
36                 File filePath = new File(dirPath);
37                 if (!filePath.exists()) {
38                     filePath.mkdirs();
39                 }
40 
41                 String newFilename = name +"_" + originalFilename;
42                 try {
43                     file.transferTo(new File(dirPath + "_"+newFilename));
44                 } catch (Exception e) {
45                     e.printStackTrace();
46                     return "error";
47                 }
48             }
49             return "success";
50         } else {
51             return "error";
52         }
53     }
54     @RequestMapping("/download.action")
55     public ResponseEntity<byte[]> filedownload(HttpServletRequest request,String filename) throws Exception{
56         String path = request.getServletContext().getRealPath("/upload");
57         File file = new File(path+File.separator+filename);
58         filename = this.getFilename(request,filename);
59         HttpHeaders headers = new HttpHeaders();
60         headers.setContentDispositionFormData("attachment",filename);
61         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
62         return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
63     }
64     public String getFilename(HttpServletRequest request,String filename) throws Exception{
65         String[] IEBrowserKeyWord = {"MSIE","Trident","Edge"};
66         String userAgent = request.getHeader("User-Agent");
67         for(String keyWord:IEBrowserKeyWord){
68             if(userAgent.contains(keyWord)){
69                 return URLEncoder.encode(filename,"UTF-8");
70             }
71         }
72         return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
73     }
74 }
FileUploadAndDownloadController

SpringMVC文件上傳和下載的實現