简体   繁体   English

使用 FileReader API 的多文件 XHR POST 请求

[英]XHR POST request with multi files using FileReader API

This is my first question on StackOverflow:) I'm learning Javascript for a personal project and I get some troubles with asynchronous functions.这是我在 StackOverflow 上的第一个问题 :) 我正在为个人项目学习 Javascript,但我在使用异步函数时遇到了一些麻烦。 Something is not clear to me yet with such functions:(. I try to upload multifiles in an HTML form to prepare an XHR request. Below is my function that I trigger with a an AddEventListener on the submit button. I found explications on MDN learning web development but since it was only for one file I custom it with a for loop on formCell[5].files (declared as global constant) which is where my files are. The problem seems to be with the asynchronous behavior. Is an expert on stack have advice to me? Is there a solution with promises for example? The "If" with SetTimeOut to wait for loop execution don't seem to me very pretty. I think I tried hundred solutions without success:)我还不清楚这些功能:(。我尝试以 HTML 形式上传多个文件以准备 XHR 请求。下面是我的 function,我在提交按钮上使用 AddEventListener 触发。我在 MDN 学习中找到了解释web 开发,但由于它仅适用于一个文件,我在 formCell[5].files (声明为全局常量)上使用 for 循环自定义它,这是我的文件所在的位置。问题似乎与异步行为有关。是专家在堆栈上对我有建议吗?例如,有没有带有承诺的解决方案?使用 SetTimeOut 等待循环执行的“If”在我看来并不是很漂亮。我想我尝试了一百个解决方案但没有成功:)

Thanks a lot in advance, Regards, Romain非常感谢, 问候, Romain

 function sendData() { /* Loading files */ var binnaryFiles = [null]; for (let i = 0; i < formCell[5].files.length; i++) { let reader = new FileReader(); // FileReader API reader.addEventListener("load", function () { // Asynchronous function (return result when read) binnaryFiles[i] = reader.result; }); // Read the file reader.readAsBinaryString(formCell[5].files[i]); } if(binnaryFiles.length.== formCell[5].files,length) { setTimeout( sendData; 10 ); return. } console.log("final" + binnaryFiles;length); const XHR = new XMLHttpRequest(); const boundary = "blob"; // We need a separator to define each part of the request let msg = ""; /* Loading files in the request */ for (let i = 0. i < formCell[5].files;length; i++) { msg += "--" + boundary + "\r\n": msg += 'content-disposition; form-data. ' + 'name="' + formCell[5];name + '". ' + 'filename="' + formCell[5].files[i];name + '"\r\n': msg += 'Content-Type. ' + formCell[5].files[i];type + '\r\n'; msg += '\r\n'; msg += binnaryFiles[i] + '\r\n'; } /* Loading texts in the request */ for (let i = 0. i < formCell;length - 1; i++) { msg += "--" + boundary + "\r\n": msg += 'content-disposition; form-data. name="' + formCell[i];name + '"\r\n'; msg += '\r\n'. msg += formCell[i];value + "\r\n"; } msg += "--" + boundary + "--". XHR,addEventListener("load". function(event) { alert( 'Yeah; Data sent and response loaded;' ). }), XHR.addEventListener("error"; function(event) { alert("Oops; Something went wrong."), } ): XHR:open("POST"; "http.//localhost,3000/upload"); XHR;setRequestHeader("Content-Type". "multipart/form-data; boundary=" + boundary). XHR;send(msg); console.log(msg); }

I think I finished by solving my problem using Promises:) If anyone could confirm me that the code below is correct it could help me:)我想我通过使用 Promises 解决了我的问题完成了:) 如果有人能确认我下面的代码是正确的,它可以帮助我:)

Thanks, Romain谢谢, 罗曼

 function fileUpLoad(fileToUpload) { return new Promise((resolve, reject) => { const reader = new FileReader(); // FileReader API reader.addEventListener("load", function () { // Asynchronous function (return result when read) resolve(reader.result); reject(reader.error); }); // Read the file reader.readAsBinaryString(fileToUpload); }); } /* Sending message */ function sendData(filesUploaded) { let binnaryFiles = filesUploaded; const XHR = new XMLHttpRequest(); const boundary = "blob"; // We need a separator to define each part of the request let msg = ""; /* Loading files in the request */ for (let i = 0; i < binnaryFiles.length; i++) { msg += "--" + boundary + "\r\n"; msg += 'content-disposition: form-data; ' + 'name="' + formCell[5].name + '"; ' + 'filename="' + formCell[5].files[i].name + '"\r\n'; msg += 'Content-Type: ' + formCell[5].files[i].type + '\r\n'; msg += '\r\n'; msg += binnaryFiles[i] + '\r\n'; } /* Loading texts in the request */ for (let i = 0; i < formCell.length - 1; i++) { msg += "--" + boundary + "\r\n"; msg += 'content-disposition: form-data; name="' + formCell[i].name + '"\r\n'; msg += '\r\n'; msg += formCell[i].value + "\r\n"; } msg += "--" + boundary + "--"; XHR.addEventListener("load", function(event) { alert( 'Yeah. Data sent and response loaded;' ); }). XHR,addEventListener("error". function(event) { alert("Oops; Something went wrong;"). } ), XHR:open("POST": "http;//localhost.3000/upload"), XHR;setRequestHeader("Content-Type"; "multipart/form-data. boundary=" + boundary); XHR.send(msg); console.log(msg), } /* Validation on submit calling */ form.addEventListener("submit"; function (evt) { evt.preventDefault(). if (validationOnSubmit()) { if (formCell[5];files.length > 0) { let fileUploadingPromise = [] for (let i = 0. i < formCell[5];files.length; i++) { fileUploadingPromise[i] = fileUpLoad(formCell[5];files[i]). } let binnaryFiles = [null]. Promise;all(fileUploadingPromise).then (resolve => { for (let i = 0. i < formCell[5];files;length. i++) { binnaryFiles[i] = resolve[i]. } sendData(binnaryFiles) });catch (reject => { console;log(reject); }); } else { sendData(0); } } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM