如何将 png 文件上传到 S3 存储桶?

How to upload a png file to S3 Bucket?

正在尝试使用 S3-for-Google-Apps-Script 库将 png 文件上传到 S3 存储桶:

// get the image blob
const imgBlob = UrlFetchApp.fetch('imageUrl').getBlob();

// init S3 instance
const s3 = S3.getInstance(awsAccessKeyId, awsSecretKey);

// upload the image to S3 bucket
s3.putObject(bucketName, 'test.png', imgBlob, { logRequests:true });

文件正在上传到 S3,但不是以完美的方式!它看起来像这样:

如果我下载图片并打开获取 error:

"It may be damaged or use a file format that Preview doesn’t recognize."

那么,如何将 .png 文件上传到亚马逊 S3 存储桶?


使用'base64'到s3.putObject()可以正确上传图片:

const base64 = Utilities.base64Encode(imgBlob.getBytes());
s3.putObject(bucketName, 'test.png', base64, { logRequests:true });
// go to S3 and clicking on the link I can see the base64 string

但这是上传为 String 例如当我进入 S3 并单击 test.png 时,我看到类似这样的内容:"iVBORw0KGgoAAAANSUhEUgAAAgAAAAI ... II=",但我想查看实际图像,而不是 String

我相信你的情况和目标如下。

  • 根据你的情况,可以上传图片的base64数据。但是,上传的数据不是图像。是字符串数据。
  • 在您的目标中,您希望使用图片 URL.
  • 上传公开共享图片的图片文件

为此,这个答案怎么样?

问题和解决方法:

当我看到"S3-for-Google-Apps-Script"的脚本时,似乎URL不能直接用于s3.putObject()。并且,输入的 blob 使用 getDataAsString() 转换为字符串类型。我认为这就是您遇到问题的原因。

在这个回答中,我建议将"S3-for-Google-Apps-Script"的GAS库修改为payload

用法:

首先请复制S3-for-Google-Apps-Script的GAS工程,修改如下

修改后的脚本:

关于S3.gs文件中的S3.prototype.putObject,请修改如下。

从:
request.setContent(object.getDataAsString());
到:
request.setContent(object.getBytes());

并且,关于S3Request.gs文件中的S3Request.prototype.setContent,请修改如下。

从:
if (typeof content != 'string') throw 'content must be passed as a string'
到:
// if (typeof content != 'string') throw 'content must be passed as a string'

并且,关于S3Request.gs文件中的S3Request.prototype.getContentMd5_,请修改如下。

从:
return Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, this.content, Utilities.Charset.UTF_8));
到:
return Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, this.content));

示例脚本:

并且,对于上述修改后的脚本,请测试以下脚本。

const imageUrl = "###";  // Please set the image URL.
const s3 = S3.getInstance(awsAccessKeyId, awsSecretKey);  // Please set them.

const imageBlob = UrlFetchApp.fetch(imageUrl).getBlob();
s3.putObject(bucketName, 'test.png', imageBlob, { logRequests:true });
  • 这样,您的令牌可以由修改后的库创建并使用它。
  • 查看this official document的时候,我以为字节数组可能可以用

参考文献: