我更大的问题是我想使用 HTML5 拖放功能通过 CORS 将图像上传到我的 S3 存储桶。我能够将某些内容放入 S3,但它总是以似乎是 base64 编码内容的形式结束。
myFileReader.readAsArrayBuffer(f);
//[...]
function on_onload(file_name, file_type, file_data) {
// file_name and file_type are bound to the function via a closure,
// file_data is passed in during the actual callback invocation.
var xhr = new XMLHttpRequest();
var fd = new FormData();
// code that sets AWS credentials for fd omitted
// _arrayBufferToBase64() just does a binary to base64 conversion
// as described in https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string
fd.append('file', _arrayBufferToBase64(file_data));
xhr.open('POST', my_aws_bucket_endpoint, true);
xhr.send(fd);
}
_arrayBufferToBase64()
只是来自 this answer 的循环代码.
尝试上传 foo.jpg
后:
$ wget [my_uri]/foo.jpg
[...]
HTTP request sent, awaiting response... 200 OK
Length: 295872 (289K) [image/jpeg]
Saving to: 'foo.jpg'
$ file foo.jpg
foo.jpg: ASCII text, with very long lines, with no line terminators
$ head -c 20 foo.jpg
/9j/4AAQSkZJRgABAQEA
如果我尝试使用 readAsBinaryString()
,如 this answer 中所述,然后将返回的数据分配给 'file'
键,没有数据被发送,我最终在我的 S3 存储桶中得到了一个零长度的文件。
最佳答案
回答我自己的问题:
事实证明,您不需要使用 FileReader
根本。 File
来自 DataTransfer
的对象事件已经与 FormData
兼容.
将文件上传到 S3 所需要做的就是在启动 XMLHttpRequest
之前通过在 FormData
中设置凭据和签名来修改该示例。到 S3。
关于javascript - 如何将 FileReader 对象中的数据转换为表单数据以供上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505574/