Ajax上传文件时获取上传文件时的进度并显示进度条

function uploadFile(){
$( ".file" ).change( function(){
var formData2 = $( this ).parent(); //得到表单
$.ajax({
url: 'xxx&r=' + Math .random(),
type: 'POST' ,
Accept: 'text/html;charset=UTF-8' ,
cache: false ,
contentType: "multipart/form-data" ,
data: new FormData(formData2[ 0 ]),
processData: false ,
contentType: false ,
xhr: function(){
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener( 'progress' , function(e){
var loaded = e.loaded; //已经上传大小情况
var tot = e.total; //附件总大小
var per = Math .floor( 100 *loaded/tot); //已经上传的百分比
$( "#son" ).html( per + "%" );
$( "#son" ).css( "width" , per + "%" );
console.log( '附件总大小 = ' + loaded);
console.log( '已经上传大小 = ' + tot);
}, false ); // for handling the progress of the upload
}
return myXhr;
},success:function(data){
console.log(data);
console.log("上传成功!!!!");
},error:function(){
console.log("上传失败!");
}
});
});
}

你可能感兴趣的:(Ajax上传文件时获取上传文件时的进度并显示进度条)