• 注册
当前位置:1313e > ajax >正文

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

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

 

首先是web.xml

 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>uploadservlet-name>
 7         <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
 8         <init-param>
 9             <param-name>contextConfigLocationparam-name>
10             <param-value>classpath:applicationContext.xmlparam-value>
11         init-param>
12         <load-on-startup>1load-on-startup>
13     servlet>
14     <servlet-mapping>
15         <servlet-name>uploadservlet-name>
16         <url-pattern>/url-pattern>
17     servlet-mapping>
18     
19     <filter>
20         <description>解决参数传递过程中的乱码问题description>
21         <filter-name>CharacterEncodingUTF8filter-name>
22         <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
23         <init-param>
24             <param-name>encodingparam-name>
25             <param-value>UTF-8param-value>
26         init-param>
27     filter>
28     <filter-mapping>
29         <filter-name>CharacterEncodingUTF8filter-name>
30         <url-pattern>/*url-pattern>
31     filter-mapping>
32 web-app>

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

 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     
13     
14     <context:component-scan base-package="com.jadyer"/>
15     
16     
17     <mvc:annotation-driven/>
18     
19     
20     
21     <mvc:resources mapping="/js/**" location="/js/"/>
22     <mvc:resources mapping="/upload/**" location="/upload/"/>
23     
24     
25     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
26         
27         <property name="maxUploadSize" value="800000"/>
28     bean>
29     
30     
31     
32     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
33         <property name="exceptionMappings">
34             <props>
35                 
36                 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileuploadprop>
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

1 <%@ page language="java" pageEncoding="UTF-8"%>
2 <h1>文件过大,请重新选择h1>

下面是用于选择文件的上传页面index.jsp

 1 <%@ page language="java" pageEncoding="UTF-8"%>
 2 
 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(//g, '');  //ajaxFileUpload会对服务器响应回来的text内容加上
text
前后缀
19 data = data.replace(//g, ''); 20 data = data.replace("
", '');
21             data = data.replace("
", ''); 22 data = data.replace("
", '');
23             data = data.replace("
", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath] 24 if(data.substring(0, 1) == 0){ //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述) 25 $("img[id='uploadImage']").attr("src", data.substring(2)); 26 $('#result').html("图片上传成功
"); 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

最后是处理文件上传的FileUploadController.java

  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"以及)
 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参数,所以前台就要用
 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         //上传多个文件时,前台表单中的所有的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下///D:/aa.jpg">能被firefox显示,而firefox是不认的
 96         out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);
 97         out.flush();
 98         return null;
 99     }
100 }

 

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录