SpringMVC结合ajaxfileupload.js实现文件无刷新上传

来源:互联网 发布:宝贝上下架时间优化 编辑:程序博客网 时间:2024/05/09 19:34

直接看代码吧,注释都在里面


首先是web.xml

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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   
  3.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  4.     <servlet>  
  5.         <description>配置SpringMVC的前端控制器</description>  
  6.         <servlet-name>upload</servlet-name>  
  7.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  8.         <init-param>  
  9.             <param-name>contextConfigLocation</param-name>  
  10.             <param-value>classpath:applicationContext.xml</param-value>  
  11.         </init-param>  
  12.         <load-on-startup>1</load-on-startup>  
  13.     </servlet>  
  14.     <servlet-mapping>  
  15.         <servlet-name>upload</servlet-name>  
  16.         <url-pattern>/</url-pattern>  
  17.     </servlet-mapping>  
  18.       
  19.     <filter>  
  20.         <description>解决参数传递过程中的乱码问题</description>  
  21.         <filter-name>CharacterEncodingUTF8</filter-name>  
  22.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  23.         <init-param>  
  24.             <param-name>encoding</param-name>  
  25.             <param-value>UTF-8</param-value>  
  26.         </init-param>  
  27.     </filter>  
  28.     <filter-mapping>  
  29.         <filter-name>CharacterEncodingUTF8</filter-name>  
  30.         <url-pattern>/*</url-pattern>  
  31.     </filter-mapping>  
  32. </web-app>  

下面是位于//src//applicationContext.xml

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.                         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  8.                         http://www.springframework.org/schema/mvc  
  9.                         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
  10.                         http://www.springframework.org/schema/context   
  11.                         http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  12.     <!-- 启动Spring的组件自动扫描机制(Spring会自动扫描base-package指定的包中的类和子包里面类) -->  
  13.     <!-- 此处可参考我的文章http://blog.csdn.net/jadyer/article/details/6038604 -->  
  14.     <context:component-scan base-package="com.jadyer"/>  
  15.       
  16.     <!-- 启动SpringMVC的注解功能,它会自动注册HandlerMapping、HandlerAdapter、ExceptionResolver的相关实例 -->  
  17.     <mvc:annotation-driven/>  
  18.       
  19.     <!-- 由于web.xml中设置SpringMVC拦截所有请求,所以在读取静态资源文件时就会读不到 -->  
  20.     <!-- 通过此配置即可指定所有请求或引用"/js/**"的资源,都会从"/js/"中查找 -->  
  21.     <mvc:resources mapping="/js/**" location="/js/"/>  
  22.     <mvc:resources mapping="/upload/**" location="/upload/"/>  
  23.       
  24.     <!-- SpringMVC上传文件时,需配置MultipartResolver处理器 -->  
  25.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  26.         <!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
  27.         <property name="maxUploadSize" value="800000"/>  
  28.     </bean>  
  29.       
  30.     <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
  31.     <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  
  32.     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  33.         <property name="exceptionMappings">  
  34.             <props>  
  35.                 <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->  
  36.                 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
  37.             </props>  
  38.         </property>  
  39.     </bean>  
  40.       
  41.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  42.         <property name="prefix" value="/WEB-INF/jsp/"/>  
  43.         <property name="suffix" value=".jsp"/>  
  44.     </bean>  
  45. </beans>  
下面是上传文件内容过大时的提示页面//WEB-INF//jsp//error_fileupload.jsp
[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <h1>文件过大,请重新选择</h1>  

下面是用于选择文件的上传页面index.jsp
[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <!-- 此处不能简写为<script type="text/javascript" src=".."/> -->  
  3. <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>  
  4. <script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>  
  5.   
  6. <script type="text/javascript">  
  7. function ajaxFileUpload(){  
  8.     //开始上传文件时显示一个图片,文件上传完成将图片隐藏  
  9.     //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});  
  10.     //执行上传文件操作的函数  
  11.     $.ajaxFileUpload({  
  12.         //处理文件上传操作的服务器端地址(可以传参数,已亲测可用)  
  13.         url:'${pageContext.request.contextPath}/test/fileUpload?uname=玄玉',  
  14.         secureuri:false,                           //是否启用安全提交,默认为false   
  15.         fileElementId:'myBlogImage',               //文件选择框的id属性  
  16.         dataType:'text',                           //服务器返回的格式,可以是json或xml等  
  17.         success:function(data, status){            //服务器响应成功时的处理函数  
  18.             data = data.replace(/<pre.*?>/g, '');  //ajaxFileUpload会对服务器响应回来的text内容加上<pre style="....">text</pre>前后缀  
  19.             data = data.replace(/<PRE.*?>/g, '');  
  20.             data = data.replace("<PRE>", '');  
  21.             data = data.replace("</PRE>", '');  
  22.             data = data.replace("<pre>", '');  
  23.             data = data.replace("</pre>", '');     //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]  
  24.             if(data.substring(0, 1) == 0){         //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)  
  25.                 $("img[id='uploadImage']").attr("src", data.substring(2));  
  26.                 $('#result').html("图片上传成功<br/>");  
  27.             }else{  
  28.                 $('#result').html('图片上传失败,请重试!!');  
  29.             }  
  30.         },  
  31.         error:function(data, status, e){ //服务器响应失败时的处理函数  
  32.             $('#result').html('图片上传失败,请重试!!');  
  33.         }  
  34.     });  
  35. }  
  36. </script>  
  37.   
  38. <div id="result"></div>  
  39. <img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">  
  40.   
  41. <input type="file" id="myBlogImage" name="myfiles"/>  
  42. <input type="button" value="上传图片" onclick="ajaxFileUpload()"/>  
  43.   
  44. <!--   
  45. AjaxFileUpload简介  
  46. 官网:http://phpletter.com/Our-Projects/AjaxFileUpload/  
  47. 简介:jQuery插件AjaxFileUpload能够实现无刷新上传文件,并且简单易用,它的使用人数很多,非常值得推荐  
  48. 注意:引入js的顺序(它依赖于jQuery)和页面中并无表单(只是在按钮点击的时候触发ajaxFileUpload()方法)  
  49. 常见错误及解决方案如下  
  50. 1)SyntaxError: missing ; before statement  
  51.   --检查URL路径是否可以访问  
  52. 2)SyntaxError: syntax error  
  53.   --检查处理提交操作的JSP文件是否存在语法错误  
  54. 3)SyntaxError: invalid property id  
  55.   --检查属性ID是否存在  
  56. 4)SyntaxError: missing } in XML expression  
  57.   --检查文件域名称是否一致或不存在  
  58. 5)其它自定义错误  
  59.   --可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多  
  60.  -->  
最后是处理文件上传的FileUploadController.java
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.jadyer.controller;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.apache.commons.io.FileUtils;  
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13. import org.springframework.web.bind.annotation.RequestParam;  
  14. import org.springframework.web.multipart.MultipartFile;  
  15.   
  16. /** 
  17.  * SpringMVC中的文件上传 
  18.  * 1)由于SpringMVC使用的是commons-fileupload实现,所以先要将其组件引入项目中 
  19.  * 2)在SpringMVC配置文件中配置MultipartResolver处理器(可在此加入对上传文件的属性限制) 
  20.  * 3)在Controller的方法中添加MultipartFile参数(该参数用于接收表单中file组件的内容) 
  21.  * 4)编写前台表单(注意enctype="multipart/form-data"以及<input type="file" name="****"/>) 
  22.  * PS:由于这里使用了ajaxfileupload.js实现无刷新上传,故本例中未使用表单 
  23.  * --------------------------------------------------------------------------------------------- 
  24.  * 这里用到了如下的jar 
  25.  * commons-io-2.4.jar 
  26.  * commons-fileupload-1.3.jar 
  27.  * commons-logging-1.1.2.jar 
  28.  * spring-aop-3.2.4.RELEASE.jar 
  29.  * spring-beans-3.2.4.RELEASE.jar 
  30.  * spring-context-3.2.4.RELEASE.jar 
  31.  * spring-core-3.2.4.RELEASE.jar 
  32.  * spring-expression-3.2.4.RELEASE.jar 
  33.  * spring-jdbc-3.2.4.RELEASE.jar 
  34.  * spring-oxm-3.2.4.RELEASE.jar 
  35.  * spring-tx-3.2.4.RELEASE.jar 
  36.  * spring-web-3.2.4.RELEASE.jar 
  37.  * spring-webmvc-3.2.4.RELEASE.jar 
  38.  * --------------------------------------------------------------------------------------------- 
  39.  * @create Sep 14, 2013 5:06:09 PM 
  40.  * @author 玄玉<http://blog.csdn.net/jadyer> 
  41.  */  
  42. @Controller  
  43. @RequestMapping("/test")  
  44. public class FileUploadController {  
  45.     /** 
  46.      * 这里这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file" name="myfiles"/> 
  47.      * 上传文件完毕后返回给前台[0`filepath],0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述) 
  48.      */  
  49.     @RequestMapping(value="/fileUpload")  
  50.     public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{  
  51.         //可以在上传文件的同时接收其它参数  
  52.         System.out.println("收到用户[" + uname + "]的文件上传请求");  
  53.         //如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中  
  54.         //这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建  
  55.         String realPath = request.getSession().getServletContext().getRealPath("/upload");  
  56.         //设置响应给前台内容的数据格式  
  57.         response.setContentType("text/plain; charset=UTF-8");  
  58.         //设置响应给前台内容的PrintWriter对象  
  59.         PrintWriter out = response.getWriter();  
  60.         //上传文件的原名(即上传前的文件名字)  
  61.         String originalFilename = null;  
  62.         //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解  
  63.         //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解  
  64.         //上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件  
  65.         for(MultipartFile myfile : myfiles){  
  66.             if(myfile.isEmpty()){  
  67.                 out.print("1`请选择文件后上传");  
  68.                 out.flush();  
  69.                 return null;  
  70.             }else{  
  71.                 originalFilename = myfile.getOriginalFilename();  
  72.                 System.out.println("文件原名: " + originalFilename);  
  73.                 System.out.println("文件名称: " + myfile.getName());  
  74.                 System.out.println("文件长度: " + myfile.getSize());  
  75.                 System.out.println("文件类型: " + myfile.getContentType());  
  76.                 System.out.println("========================================");  
  77.                 try {  
  78.                     //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉  
  79.                     //此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传  
  80.                     FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));  
  81.                 } catch (IOException e) {  
  82.                     System.out.println("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");  
  83.                     e.printStackTrace();  
  84.                     out.print("1`文件上传失败,请重试!!");  
  85.                     out.flush();  
  86.                     return null;  
  87.                 }  
  88.             }  
  89.         }  
  90.         //此时在Windows下输出的是[D:\Develop\apache-tomcat-6.0.36\webapps\AjaxFileUpload\\upload\愤怒的小鸟.jpg]  
  91.         //System.out.println(realPath + "\\" + originalFilename);  
  92.         //此时在Windows下输出的是[/AjaxFileUpload/upload/愤怒的小鸟.jpg]  
  93.         //System.out.println(request.getContextPath() + "/upload/" + originalFilename);  
  94.         //不推荐返回[realPath + "\\" + originalFilename]的值  
  95.         //因为在Windows下<img src="file:///D:/aa.jpg">能被firefox显示,而<img src="D:/aa.jpg">firefox是不认的  
  96.         out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);  
  97.         out.flush();  
  98.         return null;  
  99.     }  
  100. }  
更多1
0 0
原创粉丝点击