正在尝试上传 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,但方式并不完美!它看起来像这样:
如果我下载图像并打开得到 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/