【发布时间】:2017-10-06 04:05:24
【问题描述】:
我正在尝试提供一种解决方案,允许将文件上传到带有 C# 后端的 REST API。目前,我能够上传文件并使用 XMLHttpRequests 和 JavaScript 获取他们的上传进度。我遇到的问题是所有文件同时上传,我看到控制台消息与上传进度混合在一起。
我的问题如下:我有没有办法将表单中传入的文件名或文件信息关联起来,以便弄清楚我当前正在查看哪个文件的进度?
查看onprogress 中的e 变量,我找不到文件的任何标识符,除了文件的大小,如果上传被认为是它自己的实体,这是有意义的。
下面是我的代码,其中包含三个文件的控制台日志尝试:
HTML 表格:
<form id="uploadForm" method="post">
<input type="file" name="files[]" multiple/>
<input type="button" id="uploadButton" value="Save" />
</form>
JAVASCRIPT
$('#uploadButton').click(function () {
var files = document.forms['uploadForm']['files[]'].files; //Gather files from the form
for(var i = 0; i < files.length; i++) { //for each file
console.log(files[i].name + "; " + files[i].type + "; " + files[i].size); //log file info
var form = new FormData();
form.append(files[i].name, files[i]); //create a new form and push the file into it
var xhr = new XMLHttpRequest(); //create a new request
xhr.upload.onprogress = function (e) { //tell xmlhttprequest what to do on upload progress update
var done = e.position || e.loaded, total = e.totalSize || e.total; //onprogress function logs to console the proper percentage
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done / total * 1000) / 10) + '%');
};
xhr.open("post", "/api/contact", true); //open request
xhr.send(form); // send form
}
});
来自三个文件尝试的控制台
Index:91 1184x1600.png; image/png; 1467392
Index:91 Example.pdf; application/pdf; 65391
Index:91 FileZilla_3.27.0.1_win64-setup.exe; application/x-msdownload; 7873888
Index:98 xhr.upload progress: 65588 / 65588 = 100%
Index:98 xhr.upload progress: 65536 / 1467587 = 4.4%
Index:98 xhr.upload progress: 32768 / 7874140 = 0.4%
Index:98 xhr.upload progress: 1294336 / 1467587 = 88.1%
Index:98 xhr.upload progress: 1425408 / 7874140 = 18.1%
Index:98 xhr.upload progress: 1467587 / 1467587 = 100%
Index:98 xhr.upload progress: 3915776 / 7874140 = 49.7%
Index:98 xhr.upload progress: 6127616 / 7874140 = 77.8%
Index:98 xhr.upload progress: 7874140 / 7874140 = 100%
【问题讨论】:
标签: javascript c# xmlhttprequest