我有一个要在multipart / form-data POST请求中发送的二进制文件。我想在我的JavaScript中包含二进制文件,所以我找到了一个将Base64字符串转换为Blob的JavaScript函数,如下所示。
var b64data = 'blablabla';
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
const contentType = 'application/x-gzip';
const payload = b64toBlob(b64data, contentType);
然后我将该blob用作XMLHttpRequest发送的multipart / form-data的一部分。相关代码为:
function fileUpload(url, fileData, fileName, nameVar, ctype) {
var fileSize = fileData.length,
boundary = "ABCDEFGHIFD",
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary);
var body = "--" + boundary + "\r\n";
body += 'Content-Disposition: form-data; name="' + nameVar +'"; filename="' + fileName + '"\r\n';
body += "Content-Type: " + ctype + "\r\n\r\n";
//body += fileData;
end = "\r\n--" + boundary + "--";
//var body = fileData;
xhr.send(body + fileData + end);
return true;
}
当我将有效负载馈送到fileUpload(url,payload,fileName,nameVar,ctype);
之类的函数中时,应为二进制数据的部分只是作为[object Blob]
进行传输。如果我取出尸体并仅发送fileData,
var body = fileData;
xhr.send(body);
它传输数据包中的二进制数据。
为什么第一个函数不通过发送二进制文件?