SpringMVC 【ajax上传文件】

页面代码:

<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<link type="text/css"
    href="<%=request.getContextPath() %>/css/ajaxfileupload.css"
    rel="stylesheet" />
<script type="text/javascript"
    src="<%=request.getContextPath() %>/js/jquery-1.8.3.js"></script>
<script type="text/javascript"
    src="<%=request.getContextPath() %>/js/ajaxfileupload.js"></script>

<script type="text/javascript">
    //全局计数对象
    var i = 1;

    // 显示本地图片
    function onChangFile(seqId){
        var obj = getObjectURL(document.getElementById('file_'+seqId).files[0]);
        $('#img_'+seqId).attr('src',obj);
        
        // 文件改变,单上传功能启用
        $('#uploadButton_'+seqId).attr("disabled",false);
    };

    // 获取二进制对象
    function getObjectURL(file) {
        var url = null ; 
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    };
    
    // 添加一个单位
    function addUpload(){
        i++;
              var s = '<tr id="tr_'+i+'">';
                  s += '<td><img id="img_'+i+'" height="100" width="100" src=""></td>';
                  s += '<td><input id="file_'+i+'" type="file" name="myfiles" onchange="onChangFile(\''+i+'\')" /></td>';
                  s += '<td><input id="uploadButton_'+i+'" type="button" value="上传" disabled onclick="UploadFile(\''+i+'\')"/></td>';
                  s += '<td><button onclick="deletUpload(\''+i+'\')"><font color="red">X</font></button></td>';
                  //s += '<td><img id="img_'+i+'_'+i+'" height="100" width="100" src=""></td>';
                  s += '<td><span id="message_'+i+'"></span><span id="url_'+i+'"></span></td>';
                  s += '</tr>';
              $("#uploadtable >tbody").append(s);
              $('#file_'+i).trigger("click");
          };

    // 删除一个单位
    function deletUpload(seqId){
        $('#tr_'+seqId).remove();
    };

    //异步文件上传(jquery)
    function UploadFile(seqId) {  
        $.ajaxFileUpload({  
            url : "<%=request.getContextPath() %>/fileUpload/fileFTPUpload.do",   //submit to UploadFileServlet  
            secureuri : false,  
            fileElementId : 'file_'+seqId,  
            dataType : 'JSON', //or json xml whatever you like~  
            data: {//加入的文本参数  
                "formFieldId": "param1",  
            },  
            success : function(data, status) {  
                data = data.substring(data.indexOf("{"),data.indexOf("}")+1);
                var json = eval("(" +data+ ")");
                // 提示信息
                $("#message_"+seqId).text(json.message);   
                // url 回写
                $("#url_"+seqId).text(json.fileUrl);   
                
                $("#uploadButton_"+seqId).attr("disabled",true);
                
            },  
            error : function(data, status, e) {  
                $("#result").append(data);  
            }  
        });  
        return false;  
    }          
    
    // 批量提交
    function batchUpload(){
        
        // 所有可用按钮触发
        $("input[id^='uploadButton']").each(function(){
                 if($(this).attr("disabled")==undefined){
                     //$(this).trigger("click");
                     $(this).trigger("click");
                 }
        });
    };
</script>

</head>
<body>

    <table id="uploadtable" style="margin: auto;">
        <tbody>
            <tr id="tr_1">
            
                <td bgcolor="#aaaaaa">
                    <img id="img_1" height="100" width="100" src="">
                </td>
                <td>
                    <input id="file_1" type="file" name="myfiles" onchange="onChangFile('1')" />
                </td>
                <td>
                    <input id="uploadButton_1" type="button" value="上传" onclick="UploadFile('1')"/>
                </td>
                <td>
                    <button onclick="deletUpload('1')">
                        <font color="red">X</font>
                    </button>
                </td>
                <td>
                    <span id="message_1"></span>
                    <span id="url_1"></span>
                </td>
            </tr>
        </tbody>
    </table>
    <table style="margin: auto;">
        <tr>
            <td><input type="button" onclick="addUpload()" value="添加" />
            </td>
            <td><input type="button" onclick="batchUpload()" value="批量上传" /></td>
            <td><div id="result" style="margin-left:200px"></div></td>
        </tr>
    </table>

</body>
</html>

 

java代码:

@RequestMapping(value = "/fileFTPUpload.do", method = RequestMethod.POST)
@ResponseBody
public String handleFormUpload(
        @RequestParam("myfiles") MultipartFile fileField,
        @RequestParam(value = "formFieldId", required = false, defaultValue = "pic_url") String formFieldId,
        HttpServletRequest request, Model model) {

    System.out.println(formFieldId);

    String curDateDir = DateUtil.getCurrDateStr("yyyyMMdd");// 当天日期,用于当天的目录名称
    
    // 图片地址
    StringBuffer picUrl = new StringBuffer(request.getSession().getServletContext().getRealPath("/"));
    
    // 格式:  /picture/日期/文件名
    picUrl = picUrl.append("picture\\").append(curDateDir).append("\\");
    
    // 可行后缀
    final String[] allowedExt = new String[] { "gif", "GIF",
            "jpg", "JPG", "swf", "SWF", "PNG", "png", "FLV",
            "flv", "FLA", "fla", "jpeg" };
    
    String fileName = "";
    try {

        // 得到文件的扩展名(无扩展名时将得到全名)
        String t_ext = fileField.getContentType().substring(
                fileField.getContentType().lastIndexOf("/") + 1);
        System.out.println("文件后缀为:" + t_ext);
        
        // 判断后缀 是否 被允许
        boolean allowFlag = false;
        for ( String string : allowedExt ) {
            if ( string.equals(t_ext.toLowerCase()) ){
                allowFlag = true;
                break;
            }
        } 
        
        System.out.println("aa");
        // 后缀不符
        if ( allowFlag == false ) {
            
            String message = "请上传以下类型的文件:";
            for ( String string : allowedExt ) {
                message += " *." + string ;
            }
            message +=  "\n当前上传的文件格式为: " +t_ext;
            
            Map<String, String>map = new HashMap<String, String>();
            map.put("formFieldId", formFieldId);
            map.put("message", message);
            return JSONObject.valueToString(map);
        }
        
        // 文件 1000K 大小限制
        if ( fileField.getSize() > 1000 * 1024 ) {
            
            Map<String, String>map = new HashMap<String, String>();
            map.put("formFieldId", formFieldId);
            map.put("message", "上传文件大小不被允许!");
            return JSONObject.valueToString(map);
        }
        System.out.println("cc");
        
        // 文件名
        String name = fileField.getOriginalFilename();

        // 处理文件名
        fileName = FileUtil.dealName(name);

        // 先上传到 web
        FileUtils.copyInputStreamToFile(fileField.getInputStream(), new File(picUrl.toString(), fileName));
        
        System.out.println(picUrl.toString() + fileName);
        
        // 生成图片地址
        picUrl.append(fileName);


    }
    catch (Exception e) {
        
        e.printStackTrace();
    }
    System.out.println("ff");
    
    Map<String, String>map = new HashMap<String, String>();
    map.put("formFieldId", formFieldId);
    map.put("fileUrl", picUrl.toString());
    map.put("message", "上传成功!");
    return JSONObject.valueToString(map);
}

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    
    <!-- DispatcherServlet是一个Servlet,所以可以配置多个DispatcherServlet -->
    <servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/one-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup><!-- 启动顺序,让这个Servlet随Servlet容器一起启动 -->
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    <!-- 加了 SpringMVC Filter 之后,也只能处理post的数据乱码 -->
    <filter>  
        <filter-name>encodingFilter</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>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>

    <!-- 默认首页 -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

 

one-serlvet.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
    <!-- 自动扫描的包名(组件装配) -->
    <context:component-scan base-package="com.action" />
    
    <!-- 【视图解析器】,  根据【Controller】返回的字符串【映射】到相应的【jsp】 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
        <property name="maxUploadSize" value="100000000"/> 
        <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> 
        <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
    </bean> 
    
    <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.mvc.annotation.AnnotationMethodHandlerAdapter">
       <property name="messageConverters">
           <list>
               <ref bean="stringHttpMessageConverter" />
           </list>
       </property>
   </bean>
   
    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
           <property name ="supportedMediaTypes">   
                 <list>   
                     <value>text/plain;charset=UTF-8</value>   
                 </list>   
           </property> 
    </bean>
    
    
    <!-- 【加载】其他SpringMVC【子容器】 -->
</beans>

 

 

posted @ 2014-04-18 17:25  聆听自由  阅读(6063)  评论(0编辑  收藏  举报