直接看代碼吧,註釋都在裏面javascript
首先是web.xmlphp
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <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>
下面是位於//src//applicationContext.xmlhtml
- <?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"
- xsi:schemaLocation="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
- http://www.springframework.org/schema/context/spring-context-3.2.xsd">
-
-
- <context:component-scan base-package="com.jadyer"/>
-
-
- <mvc:annotation-driven/>
-
-
-
- <mvc:resources mapping="/js/**" location="/js/"/>
- <mvc:resources mapping="/upload/**" location="/upload/"/>
-
-
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
-
- <property name="maxUploadSize" value="800000"/>
- </bean>
-
-
-
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
-
- <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>
下面是上傳文件內容過大時的提示頁面//WEB-INF//jsp//error_fileupload.jsp
- <%@ page language="java" pageEncoding="UTF-8"%>
- <h1>文件過大,請從新選擇</h1>
下面是用於選擇文件的上傳頁面index.jsp
- <%@ page language="java" pageEncoding="UTF-8"%>
- <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.*?>/g, ''); //ajaxFileUpload會對服務器響應回來的text內容加上<pre style="....">text</pre>先後綴
- data = data.replace(/<PRE.*?>/g, '');
- data = data.replace("<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="http://www.firefox.com.cn/favicon.ico">
-
- <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直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示仍是方便不少
- -->
最後是處理文件上傳的FileUploadController.java
- 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;
-
- @Controller
- @RequestMapping("/test")
- public class FileUploadController {
-
- @RequestMapping(value="/fileUpload")
- public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{
-
- System.out.println("收到用戶[" + uname + "]的文件上傳請求");
-
-
- String realPath = request.getSession().getServletContext().getRealPath("/upload");
-
- response.setContentType("text/plain; charset=UTF-8");
-
- PrintWriter out = response.getWriter();
-
- String originalFilename = null;
-
-
-
- for(MultipartFile myfile : myfiles){
- if(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 {
-
-
- FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));
- } catch (IOException e) {
- System.out.println("文件[" + originalFilename + "]上傳失敗,堆棧軌跡以下");
- e.printStackTrace();
- out.print("1`文件上傳失敗,請重試!!");
- out.flush();
- return null;
- }
- }
- }
-
-
-
-
-
-
- out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);
- out.flush();
- return null;
- }
- } 引自:http://blog.csdn.net/jadyer/article/details/11693705