amazon-s3 - 如何将 png 文件上传到 S3 Bucket?

标签 amazon-s3 google-apps-script urlfetch

正在尝试上传 png文件使用 S3-for-Google-Apps-Script库到 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,但方式并不完美!它看起来像这样:

file image

如果我下载图像并打开得到 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数据。但是,上传的数据不是图像。这是字符串数据。
  • 在您的目标中,您希望使用图像网址上传公开共享图像的图像文件。

对于这个,这个答案怎么样?

问题和解决方法:

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

在这个答案中,我想建议修改“S3-for-Google-Apps-Script”的 GAS 库,以便使用字节数组来有效负载

用法:

首先请复制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 });
  • 这样,您的 token 就可以通过修改后的库创建并使用它。
  • 当我检查this official document时,我觉得字节数组或许可以用。

引用文献:

关于amazon-s3 - 如何将 png 文件上传到 S3 Bucket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61491801/

相关文章:

javascript - 将 Google 电子表格日期转换为 JS 日期对象?

python-2.7 - URLFetch Max Deadline 对于 TaskQueues 只有 60 秒

python - 使用 Openai 在 Google 表格中获取完整文章

java - 使用 GAE/J URLFetchServiceFactory.getURLFetchService() 的 JUnit 代码测试

amazon-web-services - S3 生命周期策略删除没有特定标记值的所有对象

c# - 如何从 lambda 函数访问 S3 存储桶中的文件

ruby-on-rails - 使用 Heroku 显示存储在 Amazon S3 上的图像

javascript - Apps 脚本 - 用逗号分割谷歌表单复选框答案

amazon-web-services - s3 原始存储桶的子目录中的 Cloudfront 默认根对象

google-apps-script - 自定义函数和重新计算