显示来自Amazon S3的与nodejs,EX pressjs和诺克斯图像 [英] showing an image from amazon s3 with nodejs, expressjs and knox

查看:213
本文介绍了显示来自Amazon S3的与nodejs,EX pressjs和诺克斯图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这应该是一个简单的事情,但我无法找到一条解决方案:■

I think this should be a straight forward thing, but I can't fing a solution :s

我想弄清楚,显示存储在Amazon S3网站上的图像的最佳方式。

I'm trying to figure out the best way to show images stored on amazon S3 on a website.

目前我试图得到这个工作(不成功)

Currently I'm trying to get this to work (unsuccessful)

//app.js
app.get('/test', function (req, res) {
    var file = fs.createWriteStream('slash-s3.jpg');
    client.getFile('guitarists/cAtiPkr.jpg', function(err, res) {
        res.on('data', function(data) { file.write(data); });
        res.on('end', function(chunk) { file.end(); });
    });
});

//index.html
<img src="/test" />

是不是,也许可以直接从亚马逊的显示图像? 我的意思是,减轻我的服务器上的负载的解决方案是最好的。

Isn't it maybe possible to show the images directly from amazon ? I mean, the solution that lightens the load on my server would be the best.

推荐答案

这是一个典型的用例。你想要做的是:请求来自Amazon S3的文件和重定向该请求(即图片)直接到客户的回答,不存储临时文件。这可以通过使用 .pipe()甲流功能。

This is a typical use case for streams. What you want to do is: request a file from Amazon S3 and redirect the answer of this request (ie. the image) directly to the client, without storing a temporary file. This can be done by using the .pipe() function of a stream.

我假设你用它来查询Amazon S3的返回流,因为你已经在使用该库。对('数据')。对(结束),它是一个流对象标准的事件。

I assume the library you use to query Amazon S3 returns a stream, as you already use .on('data') and .on('end'), which are standard events for a stream object.

下面是你如何能做到这一点:

Here is how you can do it:

app.get('/test', function (req, res) {
    client.getFile('guitarists/cAtiPkr.jpg', function(err, imageStream) {
        imageStream.pipe(res);
    });
});

通过使用管,我们重定向到直接S3至客户端的请求的输出。当请求S3关闭,这将自动终止 RES 的EX preSS。

By using pipe, we redirect the output of the request to S3 directly to the client. When the request to S3 closes, this will automatically end the res of express.

有关流的更多信息,请参阅substack的优秀流手册

For more information about streams, refer to substack's excellent Stream Handbook.

PS:小心,你的code段有两个变量命名为 RES :内部变量将屏蔽外部变量,它可能会导致很难找到错误。

PS: Be careful, in your code snippet you have two variables named res: the inner variable will mask the outer variable which could lead to hard to find bugs.

这篇关于显示来自Amazon S3的与nodejs,EX pressjs和诺克斯图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆