JQuery 【ajax上传文件】

 1.表单页面

<script type="text/javascript">  
function ajaxFileUpload() {  
    $.ajaxFileUpload({  
        url : "<%=request.getContextPath() %>/FileUploadController/upload.do",   //submit to UploadFileServlet  
        secureuri : false,  
        fileElementId : 'fileToUpload',  
        dataType : 'text', //or json xml whatever you like~  
        success : function(data, status) {  
            $("#result").append(data);  
        },  
        error : function(data, status, e) {  
            $("#result").append(data);  
        }  
    });  
    return false;  
}  

// 判断是否是图片类型
function isImage(o){
    var extArray = new Array(".jpg",".jpeg");
    var file = o.value;
    var allowSubmit = false;
    if (!file){
        return;
    }
    while (file.indexOf("\\") != -1){
        file = file.slice(file.indexOf("\\") + 1);
    }
    var ext = file.slice(file.indexOf(".")).toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
        if (extArray[i] == ext){
            allowSubmit = true;
            break;
        }
    }
    
    if (!allowSubmit){
        //清空内容
        o.value='';
        alert("只能上传以下格式的文件:\n"+ (extArray.join("\n")) + "\n请重新选择再上传.");
    }
}
</script>
<!-- upload file -->  
    <form name="form" action="<%=request.getContextPath()%>/FileUploadController/upload.do" method="POST" enctype="multipart/form-data">  
        <table class="tableForm">  
            <thead>  
                <tr>  
                    <th>JQuery Ajax File Upload</th>  
                </tr>  
            </thead>  
            <tbody>  
                <tr>  
                    <td><input id="fileToUpload"  type="file" size="45"   
                        name="myfiles"  class="input" onchange="isImage(this)"></td>  
                </tr>  
            </tbody>  
            <tfoot>  
                <tr>  
                    <td><button class="button" id="buttonUpload"  
                            onclick="return ajaxFileUpload();">Upload</button></td>  
                </tr>  
            </tfoot>  
        </table>  
        <div id="result" style="margin-left:200px"></div>  
    </form>  
    
<form action="<%=request.getContextPath()%>/FileUploadController/upload.do" method="POST" enctype="multipart/form-data"> 
    filename: <input type="text" name="filename"/><br/> 
    yourfile: <input type="file" name="myfiles" onchange="isImage(this)"/><br/> 
    yourfile: <input type="file" name="myfiles" onchange="isImage(this)"/><br/> 
    yourfile: <input type="file" name="myfiles" onchange="isImage(this)"/><br/> 
    <input type="submit" value="上传"/> 
</form> 

 2.springmvc 后台代码

    @RequestMapping("/upload.do")
    public String upload(ModelMap modelMap,
                        @RequestParam(required=false,defaultValue="") String filename,
                        @RequestParam  MultipartFile[] myfiles, 
                        HttpServletRequest request){
        System.out.println(filename);
        
         List<String> list = new ArrayList<String>();
         
         for(MultipartFile myfile : myfiles){ 
                if(myfile.isEmpty()){ 
                    System.out.println("文件未上传"); 
                }else{ 
                    if(!myfile.getContentType().startsWith("image")){
                        continue;
                    }
                    
                    System.out.println("文件长度: " + myfile.getSize()); 
                    System.out.println("文件类型: " + myfile.getContentType()); 
                    System.out.println("文件名称: " + myfile.getName()); 
                    System.out.println("文件原名: " + myfile.getOriginalFilename()); 
                    System.out.println("========================================"); 
                    //如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中 
                    String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); 
                    //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的 
                    try {
                        FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
                        list.add(realPath+"/"+myfile.getOriginalFilename());
                        
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    } 
                } 
            } 
         
         modelMap.addAttribute("pictureList", list);
         
         return "upload_success"; 
    }

3.展示页面

<%@ page language="java" pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 



<c:forEach items="${pictureList}" var="p"> 

    <img src="${p }" height="100" width="200"/>
    
</c:forEach>

4.one-servlet.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.controller" />
    
    <!-- 【视图解析器】,  根据【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="1000000"/> 
        <!-- 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> 
    
    <!-- 【加载】其他SpringMVC【子容器】 -->
</beans>

5.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>one</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>one</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>

 

 

posted @ 2014-04-15 12:15  聆听自由  阅读(751)  评论(0编辑  收藏  举报