springmvc上傳圖片並顯示圖片--支持多圖片上傳

實現上傳圖片功能在Springmvc中很好實現。如今我將會展示完整例子。html

開始須要在pom.xml加入幾個jar,分別是:java

 

[java] view plain copy
  1. <dependency>  
  2.     <groupId>commons-fileupload</groupId>  
  3.     <artifactId>commons-fileupload</artifactId>  
  4.     <version>1.3.1</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>commons-io</groupId>  
  8.     <artifactId>commons-io</artifactId>  
  9.     <version>2.4</version>  
  10. </dependency>  


接下來,在Springmvc的配置加入上傳文件的配置(PS:我把springmvc的完整配置都展示出來):web

 

[html] view plain copy
  1. <!--默認的mvc註解映射的支持 -->  
  2. <mvc:annotation-driven/>  
  3. <!-- 處理對靜態資源的請求 -->  
  4. <mvc:resources location="/static/" mapping="/static/**" />  
  5. <!-- 掃描註解 -->  
  6. <context:component-scan base-package="com.ztz.springmvc.controller"/>  
  7. <!-- 視圖解析器 -->  
  8. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  9.        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>   
  10.        <!-- 前綴 -->  
  11.     <property name="prefix" value="/WEB-INF/jsp/"/>  
  12.     <!-- 後綴 -->  
  13.     <property name="suffix" value=".jsp"/>  
  14. </bean>  
  15. <!-- 上傳文件 -->  
  16. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  17.     <property name="defaultEncoding" value="utf-8"/>  
  18.     <!-- 最大內存大小 -->  
  19.     <property name="maxInMemorySize" value="10240"/>  
  20.     <!-- 最大文件大小,-1爲不限制大小 -->  
  21.     <property name="maxUploadSize" value="-1"/>  
  22. </bean>  

 

1、 單文件上傳

固然在一個表單中,須要添加enctype="multipart/form-data",一個表單有文件域,確定也有基本的文本框,能夠一次性提交,springmvc能給咱們區別出來,來作不一樣的處理。首先看下普通的modelspring

 

[java] view plain copy
  1. package com.ztz.springmvc.model;  
  2.   
  3. public class Users {  
  4.     private String name;  
  5.     private String password;  
  6.     //省略get set方法  
  7.       
  8.     //重寫toString()方便測試  
  9.     @Override  
  10.     public String toString() {  
  11.         return "Users [name=" + name + ", password=" + password +  "]";  
  12.     }  
  13. }  


這個是表單的JSP頁面:瀏覽器

 

[java] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. request.setAttribute("basePath", basePath);  
  7. %>  
  8. <!DOCTYPE html>  
  9. <html>  
  10. <head>  
  11. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  12. <title>FileUpload</title>  
  13. </head>  
  14. <body>  
  15. <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">  
  16.     <label>用戶名:</label><input type="text" name="name"/><br/>  
  17.     <label>密 碼:</label><input type="password" name="password"/><br/>  
  18.     <label>頭 像</label><input type="file" name="file"/><br/>  
  19.     <input type="submit" value="提  交"/>  
  20. </form>  
  21. </body>  
  22. </html>  

上傳成功跳轉的JSP頁面,而且顯示出上傳圖片:mvc

 

[java] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>  
  2. <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. request.setAttribute("basePath", basePath);  
  7. %>  
  8. <!DOCTYPE html>  
  9. <html>  
  10. <head>  
  11. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  12. <title>頭像</title>  
  13. </head>  
  14. <body>  
  15. <img src="${basePath}${imagesPath}">  
  16. </body>  
  17. </html>  


最後是Controller:app

 

[java] view plain copy
  1. package com.ztz.springmvc.controller;  
  2.   
  3. import java.io.File;  
  4. import java.util.UUID;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7.   
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.RequestParam;  
  12. import org.springframework.web.multipart.MultipartFile;  
  13.   
  14. import com.ztz.springmvc.model.Users;  
  15.   
  16. @Controller  
  17. @RequestMapping("/file")  
  18. public class FileUploadController {  
  19.       
  20.     @RequestMapping(value="/upload",method=RequestMethod.POST)  
  21.     private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile file,  
  22.             HttpServletRequest request)throws Exception{  
  23.         //基本表單  
  24.         System.out.println(users.toString());  
  25.           
  26.         //得到物理路徑webapp所在路徑  
  27.         String pathRoot = request.getSession().getServletContext().getRealPath("");  
  28.         String path="";  
  29.         if(!file.isEmpty()){  
  30.             //生成uuid做爲文件名稱  
  31.             String uuid = UUID.randomUUID().toString().replaceAll("-","");  
  32.             //得到文件類型(能夠判斷若是不是圖片,禁止上傳)  
  33.             String contentType=file.getContentType();  
  34.             //得到文件後綴名稱  
  35.             String imageName=contentType.substring(contentType.indexOf("/")+1);  
  36.             path="/static/images/"+uuid+"."+imageName;  
  37.             file.transferTo(new File(pathRoot+path));  
  38.         }  
  39.         System.out.println(path);  
  40.         request.setAttribute("imagesPath", path);  
  41.         return "success";  
  42.     }  
  43.     //由於個人JSP在WEB-INF目錄下面,瀏覽器沒法直接訪問  
  44.     @RequestMapping(value="/forward")  
  45.     private String forward(){  
  46.         return "index";  
  47.     }  
  48. }  


點擊提交控制檯輸出:dom

Users [name=fileupload, password=test]
webapp


瀏覽器顯示結果:jsp



2、 多圖片上傳

springmvc實現多圖片上傳也很簡單,咱們把剛纔的例子修改下,在加一個文件域,name的值仍是相同

 

[java] view plain copy
  1. <body>  
  2. <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">  
  3.     <label>用戶名:</label><input type="text" name="name"/><br/>  
  4.     <label>密 碼:</label><input type="password" name="password"/><br/>  
  5.     <label>頭 像1</label><input type="file" name="file"/><br/>  
  6.     <label>頭 像2</label><input type="file" name="file"/><br/>  
  7.     <input type="submit" value="提  交"/>  
  8. </form>  
  9. </body>  


展現圖片來個循環,以便顯示多張圖片

 

[java] view plain copy
  1. <body>  
  2. <c:forEach items="${imagesPathList}" var="image">  
  3.     <img src="${basePath}${image}"><br/>  
  4. </c:forEach>  
  5. </body>  


控制層代碼以下:

 

[java] view plain copy
  1. package com.ztz.springmvc.controller;  
  2.   
  3. import java.io.File;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.UUID;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9.   
  10. import org.springframework.stereotype.Controller;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.RequestParam;  
  14. import org.springframework.web.multipart.MultipartFile;  
  15.   
  16. import com.ztz.springmvc.model.Users;  
  17.   
  18. @Controller  
  19. @RequestMapping("/file")  
  20. public class FileUploadController {  
  21.       
  22.     @RequestMapping(value="/upload",method=RequestMethod.POST)  
  23.     private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile[] file,  
  24.             HttpServletRequest request)throws Exception{  
  25.         //基本表單  
  26.         System.out.println(users.toString());  
  27.           
  28.         //得到物理路徑webapp所在路徑  
  29.         String pathRoot = request.getSession().getServletContext().getRealPath("");  
  30.         String path="";  
  31.         List<String> listImagePath=new ArrayList<String>();  
  32.         for (MultipartFile mf : file) {  
  33.             if(!mf.isEmpty()){  
  34.                 //生成uuid做爲文件名稱  
  35.                 String uuid = UUID.randomUUID().toString().replaceAll("-","");  
  36.                 //得到文件類型(能夠判斷若是不是圖片,禁止上傳)  
  37.                 String contentType=mf.getContentType();  
  38.                 //得到文件後綴名稱  
  39.                 String imageName=contentType.substring(contentType.indexOf("/")+1);  
  40.                 path="/static/images/"+uuid+"."+imageName;  
  41.                 mf.transferTo(new File(pathRoot+path));  
  42.                 listImagePath.add(path);  
  43.             }  
  44.         }  
  45.         System.out.println(path);  
  46.         request.setAttribute("imagesPathList", listImagePath);  
  47.         return "success";  
  48.     }  
  49.     //由於個人JSP在WEB-INF目錄下面,瀏覽器沒法直接訪問  
  50.     @RequestMapping(value="/forward")  
  51.     private String forward(){  
  52.         return "index";  
  53.     }  
  54. }  



相關文章
相關標籤/搜索