一 : applicationContext.xml中:必須聲明不然獲取不到 <!-- 上傳文件的配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="1024000"></property> <property name="defaultEncoding" value="utf-8"/><!--屬性:編碼--> </bean> 二 : 前台jsp頁面 <!-- //存放選擇文件的 圖片按鈕的 Div --> <div id="uploadfileQueue"></div> <input type="file" id="file_upload"> <img id="add_img" width="100" height="100"/> <input type="text" name="user_img" > 三 : js代碼: $(document).ready(function() { $("#file_upload").uploadify({ //是否自動上傳 true or false 'auto':true, //超時時間上傳成功后,將等待服務器的響應時間。 //在此時間后,若服務器未響應,則默認為成功(因為已經上傳,等待服務器的響應) 單位:秒 'successTimeout':99999, //附帶值 JSON對象數據,將與每個文件一起發送至服務器端。 //如果為動態值,請在onUploadStart()中使用settings()方法更改該JSON值 /* 'formData':{ //可以不寫 'user.username':'', 'user.age':'' }, */ 'onUploadStart': function(file) { $("#file_upload").uploadify( "settings" ); /* {'user.username':name,'user.age':age});*/ }, //flash 'swf': "<%=request.getContextPath()%>/uploadify/uploadify.swf", //文件選擇后的容器div的id值 'queueID':'uploadfileQueue', //將要上傳的文件對象的名稱 必須與后台controller中抓取的文件名保持一致 'fileObjName':'headerImage', //上傳地址訪問后台action路徑 'uploader':'<%=request.getContextPath()%>/photosAction/uploadFile.do', //瀏覽將要上傳文件按鈕的背景圖片路徑 //'buttonImage':'<%=request.getContextPath()%>/uplodify/background.jpg', //瀏覽按鈕的寬度 'width':'100', //瀏覽按鈕的高度 'height':'32', //在瀏覽窗口底部的文件類型下拉菜單中顯示的文本 'fileTypeDesc':'支持的格式:', //允許上傳的文件后綴 'fileTypeExts':'*.jpg;*.jpge;*.gif;*.png', //有哪些?? /*上傳文件的大小限制允許上傳文件的最大 大小。 這個值可以是一個數字或字 符串。 如果它是一個字符串,它接受一個單位(B, KB, MB, or GB)。 默認單位為KB您可以將此值設置為0 ,沒有限制, 單個文件不允許超過所設置的值 如果超過 onSelectError時間被觸發*/ 'fileSizeLimit':'1024KB', 'buttonText': '上傳頭像', //允許上傳的文件的最大數量。當達到或超過這個數字,onSelectError事件被觸發。 'queueSizeLimit' : -1, //選擇上傳文件后調用 'onSelect' : function(file) { // alert("123"); }, //返回一個錯誤,選擇文件的時候觸發 'onSelectError':function(file, errorCode, errorMsg){ switch(errorCode) { case -100: alert("上傳的文件數量已經超出系統限制的" +$('#file_upload').uploadify('settings','queueSizeLimit')+"個文件!"); break; case -110: alert("文件 ["+file.name+"] 大小超出系統限制的" +$('#file_upload').uploadify('settings','fileSizeLimit')+"大小!"); break; case -120: alert("文件 ["+file.name+"] 大小異常!"); break; case -130: alert("文件 ["+file.name+"] 類型不正確!"); break; } }, //上傳到服務器,服務器返回相應信息到data里 'onUploadSuccess':function(file, data, response){ //alert(data); $("#add_img").attr("src","<%=request.getContextPath()%>/"+data) //alert("<%=request.getContextPath()%>/"+data) $("[name='user_img']").val(data) }, //當單個文件上傳出錯時觸發 'onUploadError': function (file, errorCode, errorMsg, errorString) { alert("上傳失敗"); } }); }); 四 ; controller: @RequestMapping(value="/uploadFile",method=RequestMethod.POST) @ResponseBody public void uploadFile(@RequestParam("headerImage")CommonsMultipartFile headerImage,HttpServletRequest req,HttpServletResponse response) throws IOException{ String path = FileUtil.upFile(headerImage,req,response,"pppp"); try { response.setCharacterEncoding("utf-8"); response.getWriter().write(path); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 注意:有時候需要使用到File類型的文件 那么就需要將CommonsMultipartFile 類型的轉換為 File類型的 DiskFileItem fi = (DiskFileItem)image.getFileItem(); File file = fi.getStoreLocation(); 二 : 使用MultipartFile上傳文件(多文件) Controller層: @RequestMapping("filesUpload") public String filesUpload(@RequestParam("files") MultipartFile[] files) { //判斷file數組不能為空並且長度大於0 if(files!=null&&files.length>0){ //循環獲取file數組中得文件 for(int i = 0;i<files.length;i++){ MultipartFile file = files[i]; //保存文件 saveFile(file); } } // 重定向 return "redirect:/list.html"; } 上傳文件 private boolean saveFile(MultipartFile file) { // 判斷文件是否為空 if (!file.isEmpty()) { try { // 文件保存路徑 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename(); // 轉存文件 file.transferTo(new File(filePath)); return true; } catch (Exception e) { e.printStackTrace(); } } return false; }
SpringMVC 中,文件的上傳,是通過 MultipartResolver 實現的。 所以,如果要實現文件的上傳,只要在 spring-mvc.xml 中注冊相應的 MultipartResolver 即可。 MultipartResolver 的實現類有兩個: CommonsMultipartResolver StandardServletMultipartResolver 兩個的區別: 第一個需要使用 Apache 的 commons-fileupload 等 jar 包支持,但它能在比較舊的 servlet 版本中使用。 第二個不需要第三方 jar 包支持,它使用 servlet 內置的上傳功能,但是只能在 Servlet 3 以上的版本使用。 第一個使用步驟: /*CommonsMultipartResolver 上傳用到的兩個包*/ "commons-fileupload:commons-fileupload:1.3.1", "commons-io:commons-io:2.4" Spring_mvc.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啟mvc--> <mvc:annotation-driven/> <!-- 配置掃描發現所有具有 @Controller 注解的類,加載到容器 --> <context:component-scan base-package="text1"/> <bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp"/> </bean> <!--1 CommonsMultipartResolver 第一個需要使用 Apache 的 commons-fileupload 等 jar 包支持, 但它能在比較舊的 servlet 版本中使用--> <!-- SpringMVC上傳文件時,需要配置MultipartResolver處理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="10485760000" /> <property name="maxInMemorySize" value="40960" /> </bean> </beans> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:Spring_mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> imgTest .java java package text1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; @Controller @RequestMapping("/create") public class imgTest { @Autowired private HttpServletRequest request; @RequestMapping("/jq") public String jq() { System.out.println("oooo"); return "index"; } @RequestMapping("/upload") public String upload(MultipartFile[] mfile) throws IOException { if (mfile !=null && mfile.length>0) { for (int i = 0;i<mfile.length;i++){ long start = System.currentTimeMillis(); System.out.println("-------------------------------------------------"); System.out.println("獲取文件流"+mfile[i].getInputStream()); System.out.println("獲取文件的字節大小【byte】"+mfile[i].getSize()); System.out.println("文件類型"+mfile[i].getContentType()); System.out.println("獲取文件數據"+mfile[i].getBytes()); System.out.println("文件名字"+mfile[i].getName()); System.out.println("獲取上傳文件的原名"+mfile[i].getOriginalFilename()); System.out.println("-------------------------------------------------"); try { String filePath = request.getSession().getServletContext() .getRealPath("/") + "assets/" +start+ mfile[i].getOriginalFilename(); //轉存文件 mfile[i].transferTo(new File(filePath)); }catch (Exception e){ e.printStackTrace(); } //mfile[i].transferTo(new File("D:/ideas/"+mfile[i].getOriginalFilename()+ mfile[i].getOriginalFilename().substring( // mfile[i].getOriginalFilename().lastIndexOf(".")))); // System.out.println(mfile.getOriginalFilename()); // mfile[i].transferTo(new File("/assets" + mfile[i].getOriginalFilename())); } return "cg"; } else { System.out.println("失敗"); return "sb"; } } } html: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form:form action="/create/upload" enctype="multipart/form-data"> <input type="file" name="mfile" id="img" /><br> <input type="file" name="mfile" id="img2"/> <%--<img src="#" id="ser" >--%> <input type="submit" value="上傳圖片" /> </form:form> </body> </html> 第二個使用步驟: 這個就不要導包---建議用這個 Spring_mvc.xml 復制代碼 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啟mvc--> <mvc:annotation-driven/> <!-- 配置掃描發現所有具有 @Controller 注解的類,加載到容器 --> <context:component-scan base-package="text1"/> <bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp"/> </bean> <!--2 注冊上傳 StandardServletMultipartResolver 第二個不需要第三方 jar 包支持,它使用 servlet 內置的上傳功能, 但是只能在 Servlet 3 以上的版本使用。 --> <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"> </bean> </beans> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:Spring_mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <multipart-config> <!-- 上傳文件的大小限制,比如下面表示 5 M --> <max-file-size>5242880</max-file-size> <!-- 一次表單提交中文件的大小限制,必須下面代表 10 M --> <max-request-size>10485760</max-request-size> <!-- 多大的文件會被自動保存到硬盤上。0 代表所有 --> <file-size-threshold>0</file-size-threshold> </multipart-config> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 其他的都是一樣的。 imgTest .java 和html 這個代碼都是和上面的不變!