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

2021-08-17 10:37:52 浏览数 (1)

  • 示例
  • 测试
  • 源码

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

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

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

示例

工程结构:

UploadedFile.java

代码语言:javascript复制
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

代码语言:javascript复制
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配置文件

代码语言:javascript复制
<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">

    
    <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>


    
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    bean>


beans>

web.xml

代码语言:javascript复制
<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>springmvcservlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        servlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/config/springmvc-config.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>    
        <multipart-config>
            <max-file-size>-1max-file-size>
            <max-request-size>418018841max-request-size>
            <file-size-threshold>1048576file-size-threshold>
        multipart-config> 
    servlet>

    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

     
    <filter>  
        <filter-name>characterEncodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
        <init-param>  
            <param-name>forceEncodingparam-name>  
            <param-value>trueparam-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping> 

web-app>

前台页面:

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

代码语言:javascript复制
<html>
<head>
<script>
    var totalFileLength, totalUploaded, fileCount, filesUploaded;

    //输出调试信息
    function debug(s) { 
        var debug = document.getElementById('debug');
        if (debug) {
            debug.innerHTML = debug.innerHTML   ''   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; ivar file = files[i];
            output.push(file.name, ' (',
                  file.size, ' bytes, ',
                  file.lastModifiedDate.toLocaleDateString(), ')'
            );
            output.push('');
            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 barh1>
<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:指示了已经上传的文件数量。

测试

初始页面:

选择多个文件:

上传文件:

查看目标目录:


源码

代码已提交到github

https://github.com/yangshangwei/SpringMvcTutorialArtisan

0 人点赞