Spring MVC-09循序渐进之文件上传(基于Servlet3.0+Html5客户端上传文件)

简介: Spring MVC-09循序渐进之文件上传(基于Servlet3.0+Html5客户端上传文件)

虽然Servlet3.0+中上传文件,我们在服务端编程即可非常容易,但是用户体验却不是非常友好。单独的一个HTML表单并不能显示进度条,或者显示已经成功上传的文件数量。


不管是Java小程序,Flash 或者Silverlight都有其局限性,好在html5可以很方便的解决这些问题。


首先HTML5在其DOM中添加了一个File API,它允许访问本地文件。


示例

工程结构:

20180305233311768.png


UploadedFile.java

package com.artisan.domain;
import java.io.Serializable;
import org.springframework.web.multipart.MultipartFile;
public class UploadedFile implements Serializable {
    private static final long serialVersionUID = 72348L;
    private MultipartFile multipartFile;
    public MultipartFile getMultipartFile() {
        return multipartFile;
    }
    public void setMultipartFile(MultipartFile multipartFile) {
        this.multipartFile = multipartFile;
    }
}


Html5FileUploadController.java

package com.artisan.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.artisan.domain.UploadedFile;
@Controller
public class Html5FileUploadController {
    private static final Log logger = LogFactory
            .getLog(Html5FileUploadController.class);
    @RequestMapping(value = "/html5")
    public String inputProduct() {
        return "Html5";
    }
    @RequestMapping(value = "/file_upload")
    public void saveFile(@ModelAttribute UploadedFile uploadedFile,
            BindingResult bindingResult, Model model) {
        MultipartFile multipartFile = uploadedFile.getMultipartFile();
        logger.info("fileName:" + multipartFile.getOriginalFilename());
        String fileName = multipartFile.getOriginalFilename();
        try {
            File file = new File("D:/", fileName);
            multipartFile.transferTo(file);
            logger.info("save files successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Spring MVC配置文件

<?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:p="http://www.springframework.org/schema/p"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描控制层的注解,使其成为Spring管理的Bean -->
    <context:component-scan base-package="com.artisan.controller" />
    <!-- 静态资源文件 -->
    <mvc:annotation-driven />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/*.jsp" location="/" />
    <!-- 视图解析器 -->
    <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.support.StandardServletMultipartResolver">
    </bean>
</beans>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
        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_3_0.xsd">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>    
        <multipart-config>
            <max-file-size>-1</max-file-size>
            <max-request-size>418018841</max-request-size>
            <file-size-threshold>1048576</file-size-threshold>
        </multipart-config> 
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
     <!-- 避免中文乱码 -->
    <filter>  
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 
</web-app>



前台页面:


我们关注的是HTML5 input元素的change事件,当input元素的值发生改变时,就会被触发。其次,我们还关注XMLHttpRequest对象中添加progress事件。XMLHttpRequest自然是AJAX的骨架。当异步使用XMLHttpRequest对象上传文件的时候就会持续地触发progress事件,直到上传进度完成或者取消。通过轻松监听progress事件,可以轻松地检测文件上传操作的进度。

<!DOCTYPE HTML>
<html>
<head>
<script>
    var totalFileLength, totalUploaded, fileCount, filesUploaded;
    //输出调试信息
    function debug(s) { 
        var debug = document.getElementById('debug');
        if (debug) {
            debug.innerHTML = debug.innerHTML + '<br/>' + s;
        }
    }
    //当一个文件上传完成,紧接着开始调用下次upLoadNext();
    function onUploadComplete(e) {
        totalUploaded += document.getElementById('files').
                files[filesUploaded].size;
        filesUploaded++;
        debug('complete ' + filesUploaded + " of " + fileCount);
        debug('totalUploaded: ' + totalUploaded);        
        if (filesUploaded < fileCount) {
            uploadNext();
        } else {
            var bar = document.getElementById('bar');
            bar.style.width = '100%';
            bar.innerHTML = '100% complete';
            alert('Finished uploading file(s)');
        }
    }
    //当选择的文件发生改变时,重新获取并打印现在所选的文件信息
    function onFileSelect(e) {
        var files = e.target.files; // FileList object
        var output = [];
        fileCount = files.length;
        totalFileLength = 0;
        for (var i=0; i<fileCount; i++) {
            var file = files[i];
            output.push(file.name, ' (',
                  file.size, ' bytes, ',
                  file.lastModifiedDate.toLocaleDateString(), ')'
            );
            output.push('<br/>');
            debug('add ' + file.size);
            totalFileLength += file.size;
        }
        document.getElementById('selectedFiles').innerHTML = 
            output.join('');
        debug('totalFileLength:' + totalFileLength);
    }
   //当进度发生改变时,改变进度条
    function onUploadProgress(e) {
        if (e.lengthComputable) {
            var percentComplete = parseInt(
                    (e.loaded + totalUploaded) * 100 
                    / totalFileLength);
            var bar = document.getElementById('bar');
            bar.style.width = percentComplete + '%';
            bar.innerHTML = percentComplete + ' % complete';
        } else {
            debug('unable to compute');
        }
    }
    function onUploadFailed(e) {
        alert("Error uploading file");
    }
    //将XMLHttpRequest对象的progress事件添加到onLoadProgress并将load事件和error事件分别绑定到对应方法。
    function uploadNext() {
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        var file = document.getElementById('files').
                files[filesUploaded];
        fd.append("multipartFile", file);
        xhr.upload.addEventListener(
                "progress", onUploadProgress, false);
        xhr.addEventListener("load", onUploadComplete, false);
        xhr.addEventListener("error", onUploadFailed, false);
        xhr.open("POST", "file_upload");
        debug('uploading ' + file.name);
        xhr.send(fd);
    }
   //当用户点击提交以后开始执行
    function startUpload() {
        totalUploaded = filesUploaded = 0;
        uploadNext();
    }
    window.onload = function() {
        document.getElementById('files').addEventListener(
                'change', onFileSelect, false);
        document.getElementById('uploadButton').
                addEventListener('click', startUpload, false);
    }
</script>
</head>
<body>
<h1>Multiple file uploads with progress bar</h1>
<div id='progressBar' style='height:20px;border:2px solid green'>
    <div id='bar' 
            style='height:100%;background:#33dd33;width:0%'>
    </div>
</div>
<form>
    <input type="file" id="files" multiple/>
    <br/>
    <output id="selectedFiles"></output>
    <input id="uploadButton" type="button" value="Upload"/>
</form>
<div id='debug' 
    style='height:100px;border:2px solid green;overflow:auto'>
</div>
</body>
</html>

progressBar div用于展示上传进度,debug div用于显示调试信息。


执行脚本时,第一件事就是为4个变量分配空间:totalFileLength,totalUploaded,fileCount,filesUploaded;

- totalFileLength:主要用于保存上传文件的总长度。

- totalUploaded:指示目前已经上传的字节数。

- fileCount:包含了要上传的文件数量。

- fileUploaded:指示了已经上传的文件数量。


测试


初始页面:


20180305232957107.png

选择多个文件:


20180305233032351.png

上传文件:


2018030523305898.png


查看目标目录:

20180305233122702.png



源码


代码已提交到github

https://github.com/yangshangwei/SpringMvcTutorialArtisan


相关文章
|
13天前
|
设计模式 前端开发 Java
了解 Spring MVC 架构、Dispatcher Servlet 和 JSP 文件的关键作用
Spring MVC 是 Spring 框架的一部分,是一个 Web 应用程序框架。它旨在使用 Model-View-Controller(MVC) 设计模式轻松构建Web应用程序。
67 0
|
13天前
|
关系型数据库 MySQL
web简易开发(二){html5+php实现文件上传及通过关键字搜索已上传图片)}
web简易开发(二){html5+php实现文件上传及通过关键字搜索已上传图片)}
|
13天前
|
前端开发 Java Apache
Spring Boot文件上传与下载讲解与实战(超详细 附源码)
Spring Boot文件上传与下载讲解与实战(超详细 附源码)
533 0
|
13天前
|
安全 网络协议 Java
|
13天前
spring3 springfox报错Type javax.servlet.http.HttpServletRequest not present
spring3 springfox报错Type javax.servlet.http.HttpServletRequest not present
65 0
|
13天前
|
Java 应用服务中间件 数据库连接
Spring5源码(51)-Servlet知识点回顾以及SpringMVC分析入口
Spring5源码(51)-Servlet知识点回顾以及SpringMVC分析入口
40 0
|
13天前
|
JSON 前端开发 Java
Spring mvc-文件上传与JSON-学习笔记
Spring mvc-文件上传与JSON-学习笔记
45 2
|
13天前
|
前端开发 JavaScript Java
Spring Boot中Spring MVC的基本配置讲解与实战(包括静态资源配置,拦截器配置,文件上传配置及实战 附源码)
Spring Boot中Spring MVC的基本配置讲解与实战(包括静态资源配置,拦截器配置,文件上传配置及实战 附源码)
65 1
|
13天前
|
存储 Java 容器
SpringMVC与Servlet3.0整合实现异步处理
SpringMVC与Servlet3.0整合实现异步处理
51 1
|
13天前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
67 0