[英]How can I upload a file that is a binary string to Amazon S3 using a signed URL and JavaScript?
我在获得签名 URL 时没有遇到任何问题,文件实际上正在上传到 S3,但是当我下载文件时我无法打开它。 我试过 PDF 和图像文件。
我得到这样的文件,其中“e”是来自浏览器文件输入的文件上传事件:
let fileData = e.target.files[0];
let reader = new FileReader();
reader.readAsBinaryString(fileData); // generates a binary representation of the image
reader.onload = function(e) {
let bits = e.target.result;
let data = {
originalFilename: fileData.name,
filename: fileData.name,
mimeType: fileData.type,
fileSizeBytes: fileData.size,
lastModified: fileData.lastModified,
bin: bits
};
}
我将“数据”json 存储在 IndexeddB 中,稍后当浏览器在线时,我得到一个签名的 URL 并尝试像这样上传它:
// signedUrl is the signed URL
// data is the saved file data from the IndexeddB (above)
let contentType = data.mimeType
let binaryString = data.bin; // bin is a binary string
let formData = new FormData();
formData.append("file", btoa(data.bin));
// upload the file directly to AWS
return $.ajax({
url: signedUrl,
method: "POST",
contentType: contentType ,
data: formData,
processData: false
})
.then(function (response) {
console.log(response);
})
.catch(function (e) {
console.log('Error in file upload to AWS:');
console.log(e);
throw('Upload failed');
})
有很多示例显示如果您拥有文件 object(或者您正在使用 Postman),如何将文件发布到已签名的 URL,但是我的 web 应用程序允许用户离线“上传”文件,它们存储在 IndexeddB 中二进制字符串。 这一切都很好,我可以轻松地将文件发布到我的服务器,重新创建文件,然后将它们发送到 S3,但我想避免额外的行程。
我尝试创建一个 Blob 和其他一些东西,但我被卡住了。 任何帮助将不胜感激。
真的,我需要知道的是“在发布数据中发布到签名 URL 的文件到底是什么格式,我如何将我的文件数据转换为该格式?”
好吧,我终于知道该怎么做了。 Amazon 站点上的文档很少,web 上有很多错误信息。您只需重新创建文件 Blob(并且不要使用 fileData):
// signedUrl is the signed URL
// data is the saved file data from the IndexeddB (above)
let contentType = data.mimeType
let binaryString = data.bin; // bin is a binary string
// rebuild the file object as a Blob to send to Amazon
let bytes = new Uint8Array(binaryString.length);
for (let i=0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
let file = new Blob([bytes], {type: contentType});
// upload the file directly to AWS
return $.ajax({
url: signedUrl,
method: "POST",
contentType: false,
data: file,
processData: false
})
.then(function (response) {
console.log(response);
})
.catch(function (e) {
console.log('Error in file upload to AWS:');
console.log(e);
throw('Upload failed');
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.