gpt4 book ai didi

php - 如何使用jquery ajax php上传文件

转载 作者:行者123 更新时间:2023-12-01 05:49:32 25 4
gpt4 key购买 nike

我有一个使用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。但我想以 percentageETA(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com