【发布时间】:2017-08-10 06:42:49
【问题描述】:
目前,我正在使用@google-cloud/storage NPM 包将文件直接上传到 Google Cloud Storage 存储桶。这需要一些技巧,因为我只有图像的 base64 编码字符串。我必须:
- 解码字符串
- 另存为文件
- 将文件路径发送到以下脚本以上传到 Google Cloud Storage
- 删除本地文件
我想避免将文件完全存储在文件系统中,因为我使用的是 Google App Engine,并且我不想让文件系统过载/如果删除操作因任何原因不起作用,我不想将垃圾文件留在那里。这是我的上传脚本现在的样子:
// Convert the base64 string back to an image to upload into the Google Cloud Storage bucket
var base64Img = require('base64-img');
var filePath = base64Img.imgSync(req.body.base64Image, 'user-uploads', 'image-name');
// Instantiate the GCP Storage instance
var gcs = require('@google-cloud/storage')(),
bucket = gcs.bucket('google-cloud-storage-bucket-name');
// Upload the image to the bucket
bucket.upload(__dirname.slice(0, -15) + filePath, {
destination: 'profile-images/576dba00c1346abe12fb502a-original.jpg',
public: true,
validation: 'md5'
}, function(error, file) {
if (error) {
sails.log.error(error);
}
return res.ok('Image uploaded');
});
有没有办法直接上传图片的base64编码字符串,而不必转换成文件再使用路径上传?
【问题讨论】:
-
bucket.upload包装了file.createWriteStream函数,因此您需要将base64 文件字符串通过管道传送到file中由该方法创建的流中。我建议只写入文件系统并在上传后取消链接。我认为您在删除文件时不会遇到问题。如果您愿意,我也许可以举一个例子。 -
@forrestmid 非常感谢您如何实现
file.createWriteStream以直接上传的示例。谢谢!
标签: javascript node.js google-cloud-storage google-cloud-platform