Spring MVC-09循序渐进之文件上传(基于Servlet3.0+Html5客户端上传文件)
虽然Servlet3.0+中上传文件,我们在服务端编程即可非常容易,但是用户体验却不是非常友好。单独的一个HTML表单并不能显示进度条,或者显示已经成功上传的文件数量。
不管是Java小程序,Flash 或者Silverlight都有其局限性,好在html5可以很方便的解决这些问题。
首先HTML5在其DOM中添加了一个File API,它允许访问本地文件。
示例
工程结构:
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
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();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
前台页面:
我们关注的是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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
progressBar div用于展示上传进度,debug div用于显示调试信息。
执行脚本时,第一件事就是为4个变量分配空间:totalFileLength,totalUploaded,fileCount,filesUploaded;
- totalFileLength:主要用于保存上传文件的总长度。
- totalUploaded:指示目前已经上传的字节数。
- fileCount:包含了要上传的文件数量。
- fileUploaded:指示了已经上传的文件数量。
测试
初始页面:
选择多个文件:
上传文件:
查看目标目录:
源码
代码已提交到github
https://github.com/yangshangwei/SpringMvcTutorialArtisan
文章来源: artisan.blog.csdn.net,作者:小小工匠,版权归原作者所有,如需转载,请联系作者。
原文链接:artisan.blog.csdn.net/article/details/79452576
- 点赞
- 收藏
- 关注作者
评论(0)