javascript - 将文件名与 XMLHttpRequest 关联

标签 javascript c# xmlhttprequest

我正在尝试提供一种解决方案,允许使用 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%    

最佳答案

如果您有一个包含文件信息的对象,则可以将该对象附加到 xhr (xhr.fileInfo = {filename: ""+ files[i].name}),并且该对象应该在事件处理期间可用。

关于javascript - 将文件名与 XMLHttpRequest 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46593851/

相关文章:

javascript - Array.prototype.includes 中的错误?

基于文本框的 JavaScript URL 重定向

c# - UITableViewDelegate 中删除单元格时发生 NSInternalInconsistencyException 错误/Xamarin.iOS

c# - 从 Web API 帮助页面中排除媒体类型示例

jquery - Ajax 调用不同域 URL 时出现 401 预检错误

javascript - 如何获取使用 XMLHttpRequest (XHR2) 下载的 PNG 的像素数据

javascript - 为什么 Jquery 在使用 set minutes 函数设置时间后显示当前系统时间?

javascript - node.js - 使用 base64 的 http

c# - 无法使用 Server.MapPath

javascript - 如何捕获并覆盖每个包含 native 请求的 XHR 请求