ajax文件上传

之前一直查找无刷新上传文件的方式,在所做的项目中有无刷新上传图片的插件,但作为一个封装好的插件,打开源码也是晦涩难懂。想来仅上传这部分的东西不会太多,就继续查找和实践,终于上传成功。下面以自己能理解的方式,记录下其操作过程。

1.表单,设置其属性”enctype=”multipart/form-data”,使用FormData对象的方式进行上传

表单示例
1
2
3
4
5
<form id="form_id" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="file" name="file" />
<button onclick="uploadFile()">上传</button>

</form>

2.上传的ajax方法,uploadFile():

uploadFile
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

function uploadFile() {
var formData = new FormData($('#form_id')[0]);

$.ajax(
{
url : '/fileUploadServlet',
type : 'POST',
cache : false,
data : formData,
xhr : function() { //获取ajaxSettings中的xhr对象,为upload属性绑定progress事件的处理函数

myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { //检查upload属性是否存在
//绑定progress事件的回调函数
myXhr.upload.addEventListener('progress',
progressHandlingFunction, false);
}
return myXhr; //xhr对象返回给jQuery使用
},
processData : false,
contentType : false
}).done(function(res) {
//上传完成

}).fail(function(res) {

});
}

绑定回调函数的目的在于获取上传过程中的信息,如果要使用进度条之类的,就不必通过ajax去轮询。url为后台接受文件的servlet(java语言),可通过request.getPart()或request.getParts()获取到文件对象

3.回调函数 该函数在上传过程中触发,可获取到方法处理的信息,包括文件处理的总大小和已处理的大小,通过该数值可设置一个进度条。

回调函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14

//上传进度回调函数:
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$("#showProgress").show();
var percent = e.loaded / e.total * 100;
$('#processBar').attr("aria-valuenow", percent); //更新数据到进度条
$('#processBar').css({
'width' : percent + '%'
});
$('#percentBar').html(percent.toFixed(2) + "%");
}
}

在上述方法中,获取对象 e 中的属性计算百分比,通过此数值去设置进度条的百分比。


后台使用request.getPart()时可能会报错,需要在对应的servlet中配置如下信息:
1
2
3
4
5
6
<multipart-config>
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>