使用jQuery的文件上傳進度條我正在嘗試在我的項目中實現Ajax文件上傳功能。為此,我使用jQuery;我的代碼使用Ajax提交數據。我還想實現一個文件上傳進度條。我該怎么做?有沒有方法來計算已經上傳了多少,這樣我就可以計算上傳的百分比并創建一個進度條了嗎?
3 回答
一只斗牛犬
TA貢獻1784條經驗 獲得超2個贊
jQuery:
$(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});});HTML:
<form action="file-echo2.php" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"><br> <input type="submit" value="Upload File to Server"></form><div class="progress"> <div class="bar"></div > <div class="percent">0%</div ></div><div id="status"></div>
白豬掌柜的
TA貢獻1893條經驗 獲得超10個贊
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
if (percentComplete === 100) {
}
}
}, false);
return xhr;
},
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result) {
console.log(result);
}});
桃花長相依
TA貢獻1860條經驗 獲得超8個贊
ajax = new XMLHttpRequest();ajax.onreadystatechange = function () {
if (ajax.status) {
if (ajax.status == 200 && (ajax.readyState == 4)){
//To do tasks if any, when upload is completed
}
}}ajax.upload.addEventListener("progress", function (event) {
var percent = (event.loaded / event.total) * 100;
//**percent** variable can be used for modifying the length of your progress bar.
console.log(percent);});ajax.open("POST", 'your file upload link', true);ajax.send(formData);//ajax.send is for uploading form data.- 3 回答
- 0 關注
- 728 瀏覽
相關問題推薦
添加回答
舉報
0/150
提交
取消
