从Google Cloud存储中读取图像并使用Google Cloud功能发送

Wil*_*iro 2 node.js google-cloud-storage google-cloud-functions

我想执行以下操作:创建Google云功能(http触发),只需从存储桶(Google云端存储)中读取图像文件并将其作为响应发送.

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

'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');
};
Run Code Online (Sandbox Code Playgroud)

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

我这样做很简单,因为如果它适用于一个图像,我可以改进代码来调用任何图像.

我的最终目标是获得类似于此帖所示的内容:https: //medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556

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

Wil*_*iro 8

好吧,我可以自己找到它,我认为它可以帮助很多其他人.所以做以下事情:

1 - 在Google云端存储上创建一个存储桶,假设其名称为[my-bucket]

2 - 创建Google Cloud功能,我们将其命名为imageServer.

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

{
  "name": "image-server",
  "version": "0.0.1",
    "dependencies": {
    "@google-cloud/storage": "^1.2.1"
  }
}
Run Code Online (Sandbox Code Playgroud)

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);

};
Run Code Online (Sandbox Code Playgroud)

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

我希望它有所帮助.

参考链接: Google Cloud Storage NPM Google云功能Hello World教程