2017-10-05 24 views
0

我试图提供一个解决方案,允许将文件上传到带有C#后端的REST API。目前,我可以使用XMLHttpRequests和JavaScript上传文件并获取他们上传的进度。我遇到的问题是所有文件并发上传,并且我看到混合控制台消息和上传进度。将文件名与XMLHttpRequest关联

我的问题如下:有没有一种方法可以将表单中传入的文件名或文件信息关联起来,以便我可以确定当前正在查看哪个文件的进度?

望着onprogresse可变我无法找到任何标识符除了上载是否被认为是其自己的实体这是有道理的文件的大小的文件。

我的代码是下面的三个文件控制台日志的尝试:

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%  

回答

2

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

+0

是否有一个原因,这将通过循环循环持续,导致所有消息显示进度,但只有最后一个文件的文件名?我发誓这个工作昨天,现在它只显示最后一个文件的名字... – Ibrennan208

+0

如果你没有声明变量为本地块,你可能会得到一个不断被覆盖的全局。它可能不是对象中的文件名 - 它可能是用作显示/日志过程一部分的临时变量。 – theGleep

+0

当你说“声明变量为块的本地变量”时,你的意思是在''''onprogress'''方法中创建一个名称变量吗?或者你的意思是我应该在上传功能中创建一个名称变量? – Ibrennan208

相关问题