直接看代码吧,注释都在里面
首先是web.xml
- <?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.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"
- 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