我已经创建了一个 HTML 表单元素,如下所示用于文件上传。目前可以正确上传文件到服务器。
<form id="file_upload_form" action="http://localhost:8000/v1/file?op=upload" enctype="multipart/form-data" method="post">
<input type="file" name="xxx">
<input type="submit" value="Send">
</form>
我想通过纯jQuery/JS获取文件上传进度。我从我的研究中得到了一些如下代码来实现它。
$("#file_upload_form").submit(function(){
console.log("here");
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener( "progress", function ( evt )
{
if( evt.lengthComputable )
{
var progressPercent = ( evt.loaded / evt.total ) * 100;
console.log( progressPercent );//your function.
}
}, false );
});
但程序从未遇到过 EventListener。是否可以通过纯 jQuery/JS 为我的 HTML 表单获取文件上传进度?
最佳答案
好吧,看起来您实际上从未上传过数据,因此该程序从未遇到过 EventListener。 尝试这样的事情:
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//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;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something success-ish
}
});
在这里了解更多:JQuery ajax progress
关于javascript - 如何从 HTML 表单获取数据发布进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32421322/