我想做以下事情:创建一个Google Cloud函数(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');
};
上面的函数部署成功,但当我仅使用url (在浏览器上)触发它时,它没有显示任何结果。
我这样做尽可能简单,因为如果它对一个图像有效,我可以改进代码来调用任何图像。
我的最终目标是拥有与这篇文章中显示的类似的东西:https://medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556
而是运行在谷歌云函数上。如果我设法发送一个简单的图像,我可以使用一些模块,比如node-image-resize来得到最终的结果。
发布于 2017-08-24 19:15:18
嗯,我可以自己找到它,我认为它可以帮助很多其他人。因此,请执行以下操作:
1-在Google Cloud Storage上创建一个存储桶,假设名称为my-bucket
2-创建一个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:测试镜像是名为test-1.jpg的文件,它位于bucket的根目录下。因此,从这里,我可以将其发送到浏览器。现在只需要更改代码来实现我的主要目标,就像我在问题中所说的那样。
我希望它能帮上忙。
参考链接:Google Cloud Storage NPM Google cloud Functions Hello World tutorial
https://stackoverflow.com/questions/45850963
复制相似问题