2017-08-24 41 views
2

发送它,我想做到以下几点: 创建一个谷歌云功能(HTTP触发),简单地读一斗(谷歌云存储)的图像文件,发送它作为回应。读取图像,并使用谷歌云功能

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

'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到最后的结果。

回答

2

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

1 - 建立在谷歌云存储桶,假设名称为[我斗]

2 - 创建一个谷歌的云功能,让我们将其命名为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); 

}; 

观测数据:测试图像文件名为[ test-1.jpg]它在桶的根部。所以,从这里开始,我可以将它发送到浏览器。现在,它只是一个改变的代码来实现我的首要目标,因为我告诉我的问题的问题。

我希望它有帮助。

参考链接: Google Cloud Storage NPM Google cloud Functions Hello World tutorial