SpringMVC單文件上傳、多文件上傳、文件列表顯示、文件下載


一、新建一個Web工程,導入相關的包

springmvc的包+commons-fileupload.jar+connom-io.jar+commons-logging,jar+jstl.jar+standard.jar

整個相關的包如下:

整個工程目錄如下:

二、配置web.xml和SpringMVC文件

(1)web.xml

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.     id="WebApp_ID" version="3.0">  
  6.     <!-- SpringMVC的前端控制器 -->  
  7.     <servlet>  
  8.         <servlet-name>MyDispatcher</servlet-name>  
  9.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  10.         <!-- 設置自己定義的控制器xml文件 -->  
  11.         <init-param>  
  12.             <param-name>contextConfigLocation</param-name>  
  13.             <param-value>/WEB-INF/springMVC-servlet.xml</param-value>  
  14.         </init-param>  
  15.         <load-on-startup>1</load-on-startup>  
  16.     </servlet>  
  17.     <!-- Spring MVC配置文件結束 -->  
  18.   
  19.     <!-- 攔截設置 -->  
  20.     <servlet-mapping>  
  21.         <servlet-name>MyDispatcher</servlet-name>  
  22.         <!-- 由SpringMVC攔截所有請求 -->  
  23.         <url-pattern>/</url-pattern>  
  24.     </servlet-mapping>  
  25.       
  26. </web-app>  

(2)springMVC-servlet.xml文件

 

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:util="http://www.springframework.org/schema/util"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  5.      xmlns:mvc="http://www.springframework.org/schema/mvc"    
  6.     xsi:schemaLocation="    
  7.         http://www.springframework.org/schema/util   
  8.         http://www.springframework.org/schema/util/spring-util-3.0.xsd  
  9.         http://www.springframework.org/schema/mvc   
  10.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  11.         http://www.springframework.org/schema/beans         
  12.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  13.         http://www.springframework.org/schema/mvc      
  14.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  15.         http://www.springframework.org/schema/context     
  16.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  17.           
  18.     <!-- 把標記了@Controller注解的類轉換為bean -->  
  19.     <context:component-scan base-package="com.mucfc" />  
  20.     <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前后綴 -->  
  21.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  22.         p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>  
  23.             
  24.     <!-- 上傳文件的設置 ,maxUploadSize=-1,表示無窮大。uploadTempDir為上傳的臨時目錄 -->  
  25.    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"    
  26.         p:defaultEncoding="UTF-8"    
  27.         p:maxUploadSize="5400000"    
  28.         p:uploadTempDir="fileUpload/temp"    
  29.      />    
  30.   
  31. </beans>  

 

 

三、單個文件上傳

(1)控制器

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. @Controller  
  2. @RequestMapping("/file")  
  3. public class FileController {  
  4.   
  5.     @RequestMapping("/toFile")  
  6.     public String toFileUpload() {  
  7.         return "fileUpload";  
  8.     }  
  9.   
  10.     @RequestMapping("/toFile2")  
  11.     public String toFileUpload2() {  
  12.         return "fileUpload2";  
  13.     }  
  14.   
  15.     /** 
  16.      * 方法一上傳文件 
  17.      */  
  18.     @RequestMapping("/onefile")  
  19.     public String oneFileUpload(  
  20.             @RequestParam("file") CommonsMultipartFile file,  
  21.             HttpServletRequest request, ModelMap model) {  
  22.   
  23.         // 獲得原始文件名  
  24.         String fileName = file.getOriginalFilename();  
  25.         System.out.println("原始文件名:" + fileName);  
  26.   
  27.         // 新文件名  
  28.         String newFileName = UUID.randomUUID() + fileName;  
  29.   
  30.         // 獲得項目的路徑  
  31.         ServletContext sc = request.getSession().getServletContext();  
  32.         // 上傳位置  
  33.         String path = sc.getRealPath("/img") + "/"; // 設定文件保存的目錄  
  34.   
  35.         File f = new File(path);  
  36.         if (!f.exists())  
  37.             f.mkdirs();  
  38.         if (!file.isEmpty()) {  
  39.             try {  
  40.                 FileOutputStream fos = new FileOutputStream(path + newFileName);  
  41.                 InputStream in = file.getInputStream();  
  42.                 int b = 0;  
  43.                 while ((b = in.read()) != -1) {  
  44.                     fos.write(b);  
  45.                 }  
  46.                 fos.close();  
  47.                 in.close();  
  48.             } catch (Exception e) {  
  49.                 e.printStackTrace();  
  50.             }  
  51.         }  
  52.   
  53.         System.out.println("上傳圖片到:" + path + newFileName);  
  54.         // 保存文件地址,用於JSP頁面回顯  
  55.         model.addAttribute("fileUrl", path + newFileName);  
  56.         return "fileUpload";  
  57.     }  
  58.   
  59.     /** 
  60.      * 方法二上傳文件,一次一張 
  61.      */  
  62.     @RequestMapping("/onefile2")  
  63.     public String oneFileUpload2(HttpServletRequest request,  
  64.             HttpServletResponse response) throws Exception {  
  65.         CommonsMultipartResolver cmr = new CommonsMultipartResolver(  
  66.                 request.getServletContext());  
  67.         if (cmr.isMultipart(request)) {  
  68.             MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);  
  69.             Iterator<String> files = mRequest.getFileNames();  
  70.             while (files.hasNext()) {  
  71.                 MultipartFile mFile = mRequest.getFile(files.next());  
  72.                 if (mFile != null) {  
  73.                     String fileName = UUID.randomUUID()  
  74.                             + mFile.getOriginalFilename();  
  75.                     String path = "d:/upload/" + fileName;  
  76.   
  77.                     File localFile = new File(path);  
  78.                     mFile.transferTo(localFile);  
  79.                     request.setAttribute("fileUrl", path);  
  80.                 }  
  81.             }  
  82.         }  
  83.         return "fileUpload";  
  84.     }  
  85. }  

(2)JSP,這個頁面是用來上傳又用來顯示上傳后的圖片的頁面fileUpload.jsp

 

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  4. <%  
  5.     String path = request.getContextPath();  
  6.     String basePath = request.getScheme() + "://"  
  7.             + request.getServerName() + ":" + request.getServerPort()  
  8.             + path + "/";  
  9. %>  
  10. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  11. <html>  
  12. <head>  
  13. <title>用戶上傳圖片頁面</title>  
  14.  <base href="<%=basePath%>">  
  15. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  16. </head>  
  17. <body>  
  18.     <center>  
  19.         <form action="file/onefile"  
  20.             method="post" enctype="multipart/form-data">  
  21.             <input type="file" name="file" />   
  22.             <input type="submit" value="上 傳" />  
  23.         </form>  
  24.         <h5>上傳結果:</h5>  
  25.         <img alt="暫無圖片" src="${fileUrl}" />  
  26.     </center>  
  27. </body>  
  28. </html>  

 

 

現在運行后來看看效果,輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile

控制台輸出結果,選擇圖片后

原始文件名:Chrysanthemum.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/4eafc28c-4baa-4018-ac06-c4a5aec88d6cChrysanthemum.jpg

圖片已被上傳,可以在JSP中顯示出來

來看看服務器的路徑:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img

表明圖片已經上傳到服務器

方法二:

使用文件流的方式來上傳

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * 方法二上傳文件,一次一張 
  3.  */  
  4. @RequestMapping("/onefile2")  
  5. public String oneFileUpload2(HttpServletRequest request,  
  6.         HttpServletResponse response) throws Exception {  
  7.     CommonsMultipartResolver cmr = new CommonsMultipartResolver(  
  8.             request.getServletContext());  
  9.     if (cmr.isMultipart(request)) {  
  10.         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);  
  11.         Iterator<String> files = mRequest.getFileNames();  
  12.         while (files.hasNext()) {  
  13.             MultipartFile mFile = mRequest.getFile(files.next());  
  14.             if (mFile != null) {  
  15.                 String fileName = UUID.randomUUID()  
  16.                         + mFile.getOriginalFilename();  
  17.                 String path = "d:/upload/" + fileName;  
  18.   
  19.                 File localFile = new File(path);  
  20.                 mFile.transferTo(localFile);  
  21.                 request.setAttribute("fileUrl", path);  
  22.             }  
  23.         }  
  24.     }  
  25.     return "fileUpload";  
  26. }  

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <center>  
  2.     <form action="file/onefile"  
  3.         method="post" enctype="multipart/form-data">  
  4.         <input type="file" name="file" />   
  5.         <input type="submit" value="上 傳" />  
  6.     </form>  
  7.     <h5>上傳結果:</h5>  
  8.     <img alt="暫無圖片" src="${fileUrl}" />  
  9. </center>  

中的

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <form action="file/onefile"  

改成

 

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <form action="file/onefile2"  

輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile

 

方法二指定上傳到了本地E盤的upload文件夾

頁面結果

四、多文件上傳

(1)控制器

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. @RequestMapping("/toFile2")  
  2. public String toFileUpload2() {  
  3.     return "fileUpload2";  
  4. }  

 

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * 一次上傳多張圖片 
  3.  */  
  4. @RequestMapping("/threeFile")  
  5. public String threeFileUpload(  
  6.         @RequestParam("file") CommonsMultipartFile files[],  
  7.         HttpServletRequest request, ModelMap model) {  
  8.   
  9.     List<String> list = new ArrayList<String>();  
  10.     // 獲得項目的路徑  
  11.     ServletContext sc = request.getSession().getServletContext();  
  12.     // 上傳位置  
  13.     String path = sc.getRealPath("/img") + "/"; // 設定文件保存的目錄  
  14.     File f = new File(path);  
  15.     if (!f.exists())  
  16.         f.mkdirs();  
  17.   
  18.     for (int i = 0; i < files.length; i++) {  
  19.         // 獲得原始文件名  
  20.         String fileName = files[i].getOriginalFilename();  
  21.         System.out.println("原始文件名:" + fileName);  
  22.         // 新文件名  
  23.         String newFileName = UUID.randomUUID() + fileName;  
  24.         if (!files[i].isEmpty()) {  
  25.             try {  
  26.                 FileOutputStream fos = new FileOutputStream(path  
  27.                         + newFileName);  
  28.                 InputStream in = files[i].getInputStream();  
  29.                 int b = 0;  
  30.                 while ((b = in.read()) != -1) {  
  31.                     fos.write(b);  
  32.                 }  
  33.                 fos.close();  
  34.                 in.close();  
  35.             } catch (Exception e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.         System.out.println("上傳圖片到:" + path + newFileName);  
  40.         list.add(path + newFileName);  
  41.   
  42.     }  
  43.     // 保存文件地址,用於JSP頁面回顯  
  44.     model.addAttribute("fileList", list);  
  45.     return "fileUpload2";  
  46.   
  47. }  

其實就是在單文件上傳的方法一中來修改的,只不過弄成了個循環

 

(2)JSP顯示頁面fileUpload2.jsp

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  5. <%  
  6.     String path = request.getContextPath();  
  7.     String basePath = request.getScheme() + "://"  
  8.             + request.getServerName() + ":" + request.getServerPort()  
  9.             + path + "/";  
  10. %>  
  11. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  12. <html>  
  13. <head>  
  14. <title>用戶上傳圖片頁面</title>  
  15. <base href="<%=basePath%>">  
  16. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  17. </head>  
  18. <body>  
  19.     <center>  
  20.         <form action="file/threeFile" method="post"  
  21.             enctype="multipart/form-data">  
  22.             <input type="file" name="file" /><br /> <input type="file"  
  23.                 name="file" /><br /> <input type="file" name="file" /><br /> <input  
  24.                 type="submit" value="上 傳" />  
  25.         </form>  
  26.         <h5>上傳結果:</h5>  
  27.   
  28.         <c:forEach items="${fileList}" var="imagename">  
  29.                 <img alt="暫無圖片" src="${imagename}" /> <br/>  
  30.         </c:forEach>  
  31.   
  32.   
  33.   
  34.     </center>  
  35. </body>  
  36. </html>  

注意這里用了

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. </c:forEach>  

表單,需要jstl.jar+standard.jar

 

(3)運行后輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile2(注意上面是單文件沒有后面的數字2)

選擇圖片,然后點上傳

控制台輸出結果:

圖片不清看文字 吧:

原始文件名:Desert.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/2baccc77-43b6-4908-859d-507e86a04051Desert.jpg
原始文件名:Hydrangeas.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/51ad04e0-82aa-4b2c-958d-f00651e9ed6bHydrangeas.jpg
原始文件名:Jellyfish.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/dee340d8-9cc0-41ae-9959-f7fa47ff172bJellyfish.jpg

三張圖片都可以顯示出來了

來看看服務器,這就是剛剛上傳的三張

五、上傳文件列表顯示

(1)控制器

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.  * 列出所有的圖片 
  3.  */  
  4. @RequestMapping("/listFile")  
  5. public String listFile(HttpServletRequest request,  
  6.         HttpServletResponse response) {  
  7.     // 獲取上傳文件的目錄  
  8.     ServletContext sc = request.getSession().getServletContext();  
  9.     // 上傳位置  
  10.     String uploadFilePath = sc.getRealPath("/img") + "/"; // 設定文件保存的目錄  
  11.     // 存儲要下載的文件名  
  12.     Map<String, String> fileNameMap = new HashMap<String, String>();  
  13.     // 遞歸遍歷filepath目錄下的所有文件和目錄,將文件的文件名存儲到map集合中  
  14.     listfile(new File(uploadFilePath), fileNameMap);// File既可以代表一個文件也可以代表一個目錄  
  15.     // 將Map集合發送到listfile.jsp頁面進行顯示  
  16.     request.setAttribute("fileNameMap", fileNameMap);  
  17.     return "listFile";  
  18. }  

(2)JSP文件listFile.jsp

 

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3. <!DOCTYPE HTML>  
  4. <html>  
  5.   <head>  
  6.     <title>下載文件顯示頁面</title>  
  7.   </head>  
  8.     
  9.   <body>  
  10.       <!-- 遍歷Map集合 -->  
  11.     <c:forEach var="me" items="${fileNameMap}">  
  12.         <c:url value="/file/downFile" var="downurl">  
  13.             <c:param name="filename" value="${me.key}"></c:param>  
  14.         </c:url>  
  15.         ${me.value}<href="${downurl}">下載</a>  
  16.         <br/>  
  17.     </c:forEach>   
  18.     
  19.   </body>  
  20. </html>  


(3)運行后輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/listFile       

 

這些為剛剛上傳到四張圖片。

六、文件下載

(1)控制器

 

[html]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. @RequestMapping("/downFile")  
  2. public void downFile(HttpServletRequest request,  
  3.         HttpServletResponse response) {  
  4.     System.out.println("1");  
  5.     // 得到要下載的文件名  
  6.     String fileName = request.getParameter("filename");  
  7.     System.out.println("2");  
  8.     try {  
  9.         fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");  
  10.         System.out.println("3");  
  11.         // 獲取上傳文件的目錄  
  12.         ServletContext sc = request.getSession().getServletContext();  
  13.         System.out.println("4");  
  14.         // 上傳位置  
  15.         String fileSaveRootPath = sc.getRealPath("/img");   
  16.           
  17.         System.out.println(fileSaveRootPath + "\\" + fileName);  
  18.         // 得到要下載的文件  
  19.         File file = new File(fileSaveRootPath + "\\" + fileName);  
  20.           
  21.         // 如果文件不存在  
  22.         if (!file.exists()) {  
  23.             request.setAttribute("message", "您要下載的資源已被刪除!!");  
  24.             System.out.println("您要下載的資源已被刪除!!");  
  25.             return;  
  26.         }  
  27.         // 處理文件名  
  28.         String realname = fileName.substring(fileName.indexOf("_") + 1);  
  29.         // 設置響應頭,控制瀏覽器下載該文件  
  30.         response.setHeader("content-disposition", "attachment;filename="  
  31.                 + URLEncoder.encode(realname, "UTF-8"));  
  32.         // 讀取要下載的文件,保存到文件輸入流  
  33.         FileInputStream in = new FileInputStream(fileSaveRootPath + "\\" + fileName);  
  34.         // 創建輸出流  
  35.         OutputStream out = response.getOutputStream();  
  36.         // 創建緩沖區  
  37.         byte buffer[] = new byte[1024];  
  38.         int len = 0;  
  39.         // 循環將輸入流中的內容讀取到緩沖區當中  
  40.         while ((len = in.read(buffer)) > 0) {  
  41.             // 輸出緩沖區的內容到瀏覽器,實現文件下載  
  42.             out.write(buffer, 0, len);  
  43.         }  
  44.         // 關閉文件輸入流  
  45.         in.close();  
  46.         // 關閉輸出流  
  47.         out.close();  
  48.     } catch (Exception e) {  
  49.   
  50.     }  
  51. }  


這里就是通過文件流的方式來下載圖片的。

 

然后就可以自己選擇下載的地方了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM