Obs*_*bot 7 javascript forms html5 xmlhttprequest
我更大的问题是我想使用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);
}
Run Code Online (Sandbox Code Playgroud)
_arrayBufferToBase64()只是这个答案的循环代码.
尝试上传后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
Run Code Online (Sandbox Code Playgroud)
如果我尝试readAsBinaryString()按照本答案中的描述使用,然后将返回的数据分配给'file'密钥,则不会发送任何数据,我最终会在S3存储桶中使用零长度文件.
回答我自己的问题:
事实证明,你根本不需要使用a FileReader.File来自DataTransfer事件的对象已经兼容FormData.
将文件上传到S3所需要做的就是通过在FormData启动XMLHttpRequestS3 之前设置您的凭据和签名来修改该示例.