spring mvc实现进度上传有两种方式
1. 重写 CustomMultipartResolver 里面的方法,加个监听器。
2.本文记录另一种更简单的办法,利用jquery+html5即可实现读取文件上传进度
spring mvc xml
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
controller
@RequestMapping("/upload")
public @ResponseBody Object uploadFile(HttpServletRequest request,@RequestParam(value = "file")
MultipartFile... files)
throws
InterruptedException {
try {
for (MultipartFile f : files) {
if (f.getSize() > 0) {
File targetFile = new File("F:/a.doc");
f.transferTo(targetFile);//写入目标文件
}
}
return "ok";
} catch (Exception e) {
System.out.println("error!");
}
return null;
}
jsp
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
文件上存$(function () {
$("#upload_file").on('click', function () {
var data = new FormData();
data.append('file', $("#file")[0].files[0]);
//new FormData($('#uploadForm')[0])
$.ajax({
data: data,
url: "upload",
type: 'post',
contentType: false,
processData: false,
xhr: function () { //这是关键 获取原生的xhr对象 做以前做的所有事情
var xhr = jQuery.ajaxSettings.xhr();
xhr.upload.onload = function () {
alert('finish downloading')
}
xhr.upload.onprogress = function (evt) {
if (evt.lengthComputable) {
var progressBar = document.getElementById("progressBar");
var percentageDiv = document.getElementById("percentage");
if (evt.lengthComputable) {
var percent = evt.loaded / evt.total * 100;
console.log(percent,evt);
progressBar.max = evt.total;
progressBar.value = evt.loaded;
$(percentageDiv).html(Math.round(percent) + "%");
}
}
}
return xhr;
},
success: function () {
alert("ok");
},
error: function () {
}
});
});
});