如何使用签名 URL 和 JavaScript 将二进制字符串文件上传到 Amazon S3?

问题描述 投票:0回答:2

我在获取签名 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');
})

有很多示例展示了如果您有 File 对象(或者您正在使用 Postman),如何将文件发布到签名 URL,但我的网络应用程序允许用户离线“上传”文件,并将它们存储在 IndexeddB 中作为二进制字符串。这一切都工作正常,我可以轻松地将文件发布到我的服务器,重新创建文件,然后将它们发送到 S3,但我想避免额外的行程。

我尝试过创建 Blob 和其他一些东西,但我陷入了困境。任何帮助将不胜感激。

实际上,我需要知道的是“发布到发布数据中签名 URL 的文件到底是什么格式以及如何将我的文件数据转换为该格式?”

javascript file amazon-s3 indexeddb binary-string
2个回答
0
投票

好吧,我终于知道该怎么做了。亚马逊网站上的文档很少,网络上有很多错误信息。您只需重新创建文件 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');
})

0
投票

在 aws s3 上传时,您可以简单地传递二进制编码选项,如下所示 -

 const params = {
   Bucket: bucketName,
   Key: fileName,
  Body: Buffer.from(binaryString, "binary"), // when base64 data pass "base64"
};

s3.upload(params, (error, data) => {})
© www.soinside.com 2019 - 2024. All rights reserved.