我有一个使用jquery的formdata
的文件上传系统
事情是这样的 --->
HTML
<form id="upload-form" method="post" enctype="multipart/form-data" action="resource/php/upload.php">
<input style="display:none;" type="file" id="upload" multiple>
</form>
JQUERY
$('#upload').change(function(e){
var formdata = new FormData(),file;
$('#ajax-loader').show(); //simple gif loader
for(var i=0;i<this.files.length;i++){
file = this.files[i];
var ftype = file.type;
formdata.append("files[]", file);
}
if (formdata) {
$.ajax({
url: "resource/php/upload.php",
type: "POST",
data: formdata,
dataType : 'json',
processData: false,
contentType: false,
success: function(data) {
$('#ajax-loader').hide();
//appends the currently uploaded images in a div
}
});
}
});
PHP
//does lot of stuff
// echo's out 2 arrays in json format which is used in appending images as stated earlier^
echo json_encode(array("images"=>$db_image_id,"src"=>$db_image_src));
现在我的问题是,当我选择使用#upload
自动上传文件时,上传文件时会显示和隐藏#ajax-loader
。但我想以 percentage
和 ETA(time left)
显示进度条,替换简单的 $('#ajax-loader')
。不过,我谷歌搜索并且能够使用 ajax-form
jQuery 插件来做到这一点。但我想做更实际的事情,我不想使用任何插件。我将如何做到这一点?
还有一个问题是是否有必要使用#upload-form
?
最佳答案
需要编写custome xhr函数来实现跟踪文件上传进度
$.ajax({
url: "resource/php/upload.php",
type: "POST",
data: formdata,
dataType : 'json',
processData: false,
contentType: false,
//@custome xhr
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//@custome xhr end
success: function(data) {
$('#ajax-loader').hide();
//appends the currently uploaded images in a div
}
});
参见上面代码中的注释@custome xhr,并添加更新进度条的功能
function updateProgress(evt) {
console.log('updateProgress');
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
} else {
// Unable to compute progress information since the total size is unknown
console.log('unable to complete');
}
}
引用号:https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
关于php - 如何使用jquery ajax php上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23711831/