【问题标题】:Associating Filename with XMLHttpRequest将文件名与 XMLHttpRequest 关联
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 这是否会在循环周期中持续存在,导致所有消息显示进度但仅显示最后一个文件的文件名?我发誓这昨天有效,现在它只显示最后一个文件的名称......
    • 如果你不将变量声明为块的本地变量,你最终可能会得到一个不断被覆盖的全局变量。它可能不是对象中的文件名 - 它可能是用作显示/日志过程的一部分的临时变量。
    • 当您说“将变量声明为块的本地变量”时,您的意思是在 onprogress 方法中创建名称变量吗?或者你的意思是我应该在上传函数中创建一个名称变量?
    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多