快速缓存来自 Google Cloud Storage 的图像流

问题描述 投票:0回答:1

我正在使用 Express 4 提供图像流:

app.get('/v1/images/:Uid/', function(req, res) {
    var gcsbucket = gcs.bucket('bucket'),
    remoteReadStream = gcsbucket.file(req.params.Uid+'.jpg').createReadStream();
    remoteReadStream.pipe(res);
});

(图片存储在Google云存储中)

我正在尝试找到一种方法来告诉浏览器缓存我正在提供的图像。 我尝试添加:

res.set('Cache-Control', 'public, max-age=31557600');

但是当我访问 http://server/v1/images/1234 的 API 时,这并没有改变任何东西,它总是重新加载图像。

使用流服务器端时告诉浏览器缓存响应的正确方法是什么?

node.js express stream google-cloud-storage
1个回答
1
投票

这确实有效:

const { Storage } = require('@google-cloud/storage');

// Creates a Google Cloud Storage client
const gcs = new Storage();  

// ... create Express server app here (omitted for brevity)

app.get('/v1/images/:Uid/', function(req, res) {
    const gcsbucket = gcs.bucket('bucket'),
    const remoteReadStream = gcsbucket.file(req.params.Uid+'.jpg').createReadStream();
    res.set('Cache-Control', 'public, max-age=31557600');
    remoteReadStream.pipe(res);
});

奇怪的是,当你直接访问 API 时,浏览器从不缓存。然而,当您将图像嵌入到 html 页面中时,图像会被缓存:

<img src="http://server/v1/images/1234">

这对于我的用例来说已经足够了,但是如果有人有原因吗?

© www.soinside.com 2019 - 2024. All rights reserved.