`

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" 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">
    <!-- 启动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>

 下面是上传文件内容过大时的提示页面//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=".."/> -->
<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="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;
 
/**
 * 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){
            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 {
                    //这里不必处理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;
                }
            }
        }
        //此时在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;
    }
}

 

在本文的最后提供了ajaxfileupload.js的下载

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics