从Google云端存储中读取图片,并使用Google云端function进行发送

我想执行以下操作:创buildGoogle Cloud Function(http触发),只需从存储桶中读取图像文件(Google Cloud Storage)并将其作为响应发送。

我试过一些组合,我认为它应该是这样的:

'use strict'; const gcs = require('@google-cloud/storage')(); exports.sendImage = function sendImage(req, res) { let bucket = gcs.bucket('my-bucket-name'); let myImage = bucket.file('my-image-file.jpg'); res.contentType('image/jpeg'); res.end(myImage, 'binary'); }; 

上面的function部署成功,但是当我触发它只是使用url(在浏览器),它没有显示任何结果。

我尽可能简单地做到这一点,因为如果它与一个图像一起工作,我可以改进代码来调用任何图像。

我的最终目标是在此post中显示类似的内容: https : //medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556

但在Google Cloud Functions上运行。 如果我设法发送一个简单的图像,我可以使用一些模块,如node-image-resize到最终结果。

那么我可以自己find它,我认为它可以帮助很多其他人。 所以做以下几点:

1 – 在Google云端存储上创build存储分区,假设名称是[my-bucket]

2 – 创build一个Google Cloud Function,我们将其命名为imageServer。

3 – 不要忘记编辑package.json文件。 我的一个如下:

 { "name": "image-server", "version": "0.0.1", "dependencies": { "@google-cloud/storage": "^1.2.1" } } 

4 – 发送简单图像的代码非常简单(在我明白之后):

 'use strict'; const gcs = require('@google-cloud/storage')(); exports.imageServer = function imageSender(req, res) { let file = gcs.bucket('my-bucket').file('test-1.jpg'); let readStream = file.createReadStream(); res.setHeader("content-type", "image/jpeg"); readStream.pipe(res); }; 

Obs:testing图像是一个名为[test-1.jpg]的文件,它位于桶的根部。 所以,从这里,我能够把它发送到浏览器。 现在只是改变代码来实现我的主要目标,就像我在我的问题上讲的那样。

我希望它有帮助。

参考链接: Google Cloud Storage NPM Google云端函数Hello World教程