通过多部分POST请求发送二进制文件的方式如下:
var xhr = new XMLHttpRequest();
body = '--' + boundary + '\r\n'
+ 'Content-Disposition: form-data; name="file"; '
+ 'filename="temp.bin"\r\n'
+ 'Content-type: application/octet-stream\r\n\r\n'
+ encryptedFileContent + '\r\n'
+ '--' + boundary + '--';
xhr.open("POST", "http://localhost:999/some/path", true);
xhr.setRequestHeader("Content-type", "multipart/form-data; boundary="+boundary);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
console.log("File uploaded!");
}
xhr.send(body);我将它发送到一个铬包装的应用程序中,而我以这种方式发送文件的原因是,最初该文件是通过FileReader从本地文件系统读取的,然后在提交之前对其进行加密。encryptedFileContent是以以下方式构建的:
var reader = new FileReader();
reader.onload = function(e) {
var plainArray = Array.apply([], new Int8Array(e.target.result));
var encryptedArray = encrypt(plainArray);
var encryptedFileContent="";
for (var i=0; i<encryptedArray.length; i++) {
encryptedFileContent+=String.fromCharCode(encryptedArray[i])
}
}
reader.readAsArrayBuffer(file);调试时,我可以看到encryptedArray包含以下值:
[ 70, -21, -15, ... ]在服务器端,当读取数组时,我希望看到相同的数据,但我看到的是:
[ -17, -66, -112, ... ]看起来我为二进制文件构建有效负载的方式是不正确的。String.fromCharCode是问题所在吗?
发布于 2014-01-27 09:19:15
服务器上接收的字节数组之所以不同,是因为有效负载被转换为unicode并编码为utf-8。为了在不进行任何转换的情况下发送数据,您应该以二进制方式发送数据,如下所述:
if (!XMLHttpRequest.prototype.sendAsBinary) {
XMLHttpRequest.prototype.sendAsBinary = function(sData) {
var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
for (var nIdx = 0; nIdx < nBytes; nIdx++) {
ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
}
/* send as ArrayBufferView...: */
this.send(ui8Data);
/* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
};
}https://stackoverflow.com/questions/21358176
复制相似问题