【发布时间】:2021-02-10 06:48:07
【问题描述】:
这是我在 StackOverflow 上的第一个问题 :) 我正在为个人项目学习 Javascript,但在使用异步函数时遇到了一些麻烦。我还不清楚这些功能:(。 我尝试以 HTML 表单上传多文件以准备 XHR 请求。下面是我在提交按钮上使用 AddEventListener 触发的函数。 我找到了关于 MDN 学习 Web 开发的说明,但由于它仅适用于一个文件,因此我在 formCell[5].files(声明为全局常量)上使用 for 循环自定义它,这是我的文件所在的位置。 问题似乎与异步行为有关。堆栈专家对我有建议吗?例如,有没有带有承诺的解决方案?使用 SetTimeOut 等待循环执行的“If”在我看来不是很漂亮。 我想我尝试了一百个解决方案但没有成功:)
提前非常感谢, 问候, 罗曼
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);
}
【问题讨论】:
标签: javascript forms xmlhttprequest filereader multifile-uploader