gpt4 book ai didi

javascript - 带进度条的 Ajax 请求

转载 作者:行者123 更新时间:2023-12-01 04:34:38 24 4
gpt4 key购买 nike

我有一个将图像上传到 Imgur API 的 Ajax 请求,我需要在上传时向用户显示进度条,我按照此 thread 中提供的说明进行操作。但它只显示 1,之后就不起作用了。这是我当前正在使用的代码

var settings = {
"xhr": function(){
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
("#progressbar").html"percentComplete)
("#progressbar").css("width",precentComplete)
//Do something with upload progress
console.log(percentComplete);
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;

//Do something with download progress
console.log(percentComplete);
}
}, false);
return xhr;
},
"async": true,
"crossDomain": true,
"url": "https://api.imgur.com/3/upload",
"method": "POST",
"headers": {
"Authorization": "Client-ID <client-id>",
"cache-control": "no-cache",
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}

$.ajax(settings).done(function (response) {
console.log(response);
let json = JSON.parse(response)
$("#prd-url").val(json.data.link)
$("#prd-image").html("Change Image");
$("#submit-prd-btn").attr("disabled",false);

});
#button {
width: 100%;
background-color: #ddd;
}

#progressbar {
width: 1%;
height: 30px;
background-color: #4CAF50;
}

<div id="button">
<div id="progressbar"></div>
</div>

有没有办法在文件上传之前显示进度条,我需要一个基于百分比的进度条。允许上传的最大图像大小为 2mb,我尝试上传 1.8mb 和 200kb 图像,在发送 Ajax 调用后均发送 1,但在 2 秒延迟后才发送 Ajax 调用的响应 enter image description here

最佳答案

像这样更新 xhr 函数

xhr: function() {
var xhr = new window.XMLHttpRequest();
var progressBar = $("#progressbar");
//Upload progress
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded/evt.total)*100;
percentComplete = Math.floor(percentComplete);
console.log(percentComplete);
progressBar.css("width", percentComplete + "%");
progressBar.html(percentComplete+'%');
}
}, false);
return xhr;
},

下载时也执行相同的操作。

关于javascript - 带进度条的 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550158/

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