SpringMVC結合ajaxfileupload.js實現文件無刷新上傳
直接看代碼吧,注釋都在里面
首先是web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee ; <servlet> <description>配置SpringMVC的前端控制器</description> <servlet-name>upload</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping><filter> <description>解決參數傳遞過程中的亂碼問題</description> <filter-name>CharacterEncodingUTF8</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingUTF8</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
</web-app></pre>
下面是位于//src//applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context ; <!-- 啟動Spring的組件自動掃描機制(Spring會自動掃描base-package指定的包中的類和子包里面類) --> <!-- 此處可參考我的文章http://blog.csdn.net/jadyer/article/details/6038604 --> <context:component-scan base-package="com.jadyer"/><!-- 啟動SpringMVC的注解功能,它會自動注冊HandlerMapping、HandlerAdapter、ExceptionResolver的相關實例 --> <mvc:annotation-driven/> <!-- 由于web.xml中設置SpringMVC攔截所有請求,所以在讀取靜態資源文件時就會讀不到 --> <!-- 通過此配置即可指定所有請求或引用"/js/**"的資源,都會從"/js/"中查找 --> <mvc:resources mapping="/js/**" location="/js/"/> <mvc:resources mapping="/upload/**" location="/upload/"/> <!-- SpringMVC上傳文件時,需配置MultipartResolver處理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 指定所上傳文件的總大小不能超過800KB......注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件的容量之和 --> <property name="maxUploadSize" value="800000"/> </bean> <!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,而且此時還沒有進入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> </props> </property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
</beans></pre>下面是上傳文件內容過大時的提示頁面//WEB-INF//jsp//error_fileupload.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <h1>文件過大,請重新選擇</h1>
下面是用于選擇文件的上傳頁面index.jsp</strong></span>
<%@ page language="java" pageEncoding="UTF-8"%> <!-- 此處不能簡寫為<script type="text/javascript" src=".."/> --> <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script><script type="text/javascript"> function ajaxFileUpload(){ //開始上傳文件時顯示一個圖片,文件上傳完成將圖片隱藏 //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();}); //執行上傳文件操作的函數 $.ajaxFileUpload({ //處理文件上傳操作的服務器端地址(可以傳參數,已親測可用) url:'${pageContext.request.contextPath}/test/fileUpload?uname=玄玉', secureuri:false, //是否啟用安全提交,默認為false fileElementId:'myBlogImage', //文件選擇框的id屬性 dataType:'text', //服務器返回的格式,可以是json或xml等 success:function(data, status){ //服務器響應成功時的處理函數 data = data.replace("<PRE>", ''); //ajaxFileUpload會對服務器響應回來的text內容加上<pre>text</pre>前后綴 data = data.replace("</PRE>", ''); data = data.replace("<pre>", ''); data = data.replace("</pre>", ''); //本例中設定上傳文件完畢后,服務端會返回給前臺[0`filepath] if(data.substring(0, 1) == 0){ //0表示上傳成功(后跟上傳后的文件路徑),1表示失敗(后跟失敗描述) $("img[id='uploadImage']").attr("src", data.substring(2)); $('#result').html("圖片上傳成功<br/>"); }else{ $('#result').html('圖片上傳失敗,請重試!!'); } }, error:function(data, status, e){ //服務器響應失敗時的處理函數 $('#result').html('圖片上傳失敗,請重試!!'); } }); } </script>
<div id="result"></div> <img id="uploadImage" src=";
<input type="file" id="myBlogImage" name="myfiles"/> <input type="button" value="上傳圖片" onclick="ajaxFileUpload()"/>
<!-- AjaxFileUpload簡介 官網:http://phpletter.com/Our-Projects/AjaxFileUpload/ 簡介:jQuery插件AjaxFileUpload能夠實現無刷新上傳文件,并且簡單易用,它的使用人數很多,非常值得推薦 注意:引入js的順序(它依賴于jQuery)和頁面中并無表單(只是在按鈕點擊的時候觸發ajaxFileUpload()方法) 常見錯誤及解決方案如下 1)SyntaxError: missing ; before statement --檢查URL路徑是否可以訪問 2)SyntaxError: syntax error --檢查處理提交操作的JSP文件是否存在語法錯誤 3)SyntaxError: invalid property id --檢查屬性ID是否存在 4)SyntaxError: missing } in XML expression --檢查文件域名稱是否一致或不存在 5)其它自定義錯誤 --可使用變量$error直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多 --></pre>最后是處理文件上傳的FileUploadController.java</strong></span>
package com.jadyer.controller;import java.io.File; import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile;
/**
- SpringMVC中的文件上傳
- 1)由于SpringMVC使用的是commons-fileupload實現,所以先要將其組件引入項目中
- 2)在SpringMVC配置文件中配置MultipartResolver處理器(可在此加入對上傳文件的屬性限制)
- 3)在Controller的方法中添加MultipartFile參數(該參數用于接收表單中file組件的內容)
- 4)編寫前臺表單(注意enctype="multipart/form-data"以及<input type="file" name="**"/>)
- PS:由于這里使用了ajaxfileupload.js實現無刷新上傳,故本例中未使用表單
- 這里用到了如下的jar
- commons-io-2.4.jar
- commons-fileupload-1.3.jar
- commons-logging-1.1.2.jar
- spring-aop-3.2.4.RELEASE.jar
- spring-beans-3.2.4.RELEASE.jar
- spring-context-3.2.4.RELEASE.jar
- spring-core-3.2.4.RELEASE.jar
- spring-expression-3.2.4.RELEASE.jar
- spring-jdbc-3.2.4.RELEASE.jar
- spring-oxm-3.2.4.RELEASE.jar
- spring-tx-3.2.4.RELEASE.jar
- spring-web-3.2.4.RELEASE.jar
- spring-webmvc-3.2.4.RELEASE.jar
- @create Sep 14, 2013 5:06:09 PM
- @author 玄玉<http://blog.csdn.net/jadyer> */ @Controller @RequestMapping("/test") public class FileUploadController { /**
- 這里這里用的是MultipartFile[] myfiles參數,所以前臺就要用<input type="file" name="myfiles"/>
- 上傳文件完畢后返回給前臺[0`filepath],0表示上傳成功(后跟上傳后的文件路徑),1表示失敗(后跟失敗描述) */ @RequestMapping(value="/fileUpload") public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{ //可以在上傳文件的同時接收其它參數 System.out.println("收到用戶[" + uname + "]的文件上傳請求"); //如果用的是Tomcat服務器,則文件會上傳到\%TOMCAT_HOME%\webapps\YourWebProject\upload\文件夾中 //這里實現文件上傳操作用的是commons.io.FileUtils類,它會自動判斷/upload是否存在,不存在會自動創建 String realPath = request.getSession().getServletContext().getRealPath("/upload"); //設置響應給前臺內容的數據格式 response.setContentType("text/plain; charset=UTF-8"); //設置響應給前臺內容的PrintWriter對象 PrintWriter out = response.getWriter(); //上傳文件的原名(即上傳前的文件名字) String originalFilename = null; //如果只是上傳一個文件,則只需要MultipartFile類型接收文件即可,而且無需顯式指定@RequestParam注解 //如果想上傳多個文件,那么這里就要用MultipartFile[]類型來接收文件,并且要指定@RequestParam注解 //上傳多個文件時,前臺表單中的所有<input type="file"/>的name都應該是myfiles,否則參數里的myfiles無法獲取到所有上傳的文件 for(MultipartFile myfile : myfiles){
} //此時在Windows下輸出的是[D:\Develop\apache-tomcat-6.0.36\webapps\AjaxFileUpload\upload\憤怒的小鳥.jpg] //System.out.println(realPath + "\" + originalFilename); //此時在Windows下輸出的是[/AjaxFileUpload/upload/憤怒的小鳥.jpg] //System.out.println(request.getContextPath() + "/upload/" + originalFilename); //不推薦返回[realPath + "\" + originalFilename]的值 //因為在Windows下<img src="file:///D:/aa.jpg">能被firefox顯示,而<img src="D:/aa.jpg">firefox是不認的 out.print("0`" + request.getContextPath() + "/upload/" + originalFilename); out.flush(); return null; } }</pre>來自:http://blog.csdn.net/jadyer/article/details/11693705if(myfile.isEmpty()){ out.print("1`請選擇文件后上傳"); out.flush(); return null; }else{ originalFilename = myfile.getOriginalFilename(); System.out.println("文件原名: " + originalFilename); System.out.println("文件名稱: " + myfile.getName()); System.out.println("文件長度: " + myfile.getSize()); System.out.println("文件類型: " + myfile.getContentType()); System.out.println("========================================"); try { //這里不必處理IO流關閉的問題,因為FileUtils.copyInputStreamToFile()方法內部會自動把用到的IO流關掉 //此處也可以使用Spring提供的MultipartFile.transferTo(File dest)方法實現文件的上傳 FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename)); } catch (IOException e) { System.out.println("文件[" + originalFilename + "]上傳失敗,堆棧軌跡如下"); e.printStackTrace(); out.print("1`文件上傳失敗,請重試!!"); out.flush(); return null; } }