我有一个快速应用程序托管在谷歌AppEngine
使用快速静态中间件。我想将静态文件存储在google-cloud-storage
上,并且能够在没有太多修改的情况下从常规文件系统切换到google-cloud-storage
。
我在考虑编写一个中间件:
google-cloud-storage
网址)。有更简单/更清洁的方法吗?
您可以使用configure a GCS bucket to host a static website然后使用an existing express中间件来代理对该存储桶的请求。
您也可以使用像s3-proxy这样的s3 express中间件。通过遵循“简单”迁移步骤来移动s3 client application to google cloud storage,您应该能够为中间件派生必要的配置参数。关键的一步是产生一些'访问'和'秘密'developer keys。
我使用http-proxy-middleware完成了这项工作。基本上,由于可以通过http协议访问GCS文件,这就是我们所需要的。
理想情况下,文件可以直接从GCS本身提供,方法是将存储桶公开并使其URL像https://storage.googleapis.com/<bucket-name>/file
一样。但我的要求是需要从与我的应用程序相同的域提供文件,但文件不是应用程序本身的一部分(它们是单独生成的)。所以,我必须将其作为代理实现。
import proxy from 'http-proxy-middleware';
...
app.use('/public', proxy({
target: `https://storage.googleapis.com/${process.env.GOOGLE_CLOUD_PROJECT}.appspot.com`,
changeOrigin: true,
}));
请注意,基于项目ID的存储桶由GAE自动创建,但需要提供公共访问权限。这可以通过
gsutil defacl set public-read gs://${GOOGLE_CLOUD_PROJECT}.appspot.com
设置代理后,所有对https://example.com/public/ *的请求都将从桶<GOOGLE_CLOUD_PROJECT>.appspot.com/public/*
提供。
我需要相同的并遇到google cloud node上使用的示例或在另一个问题中查看example
将文件内容的读取流传输到您的响应。设置文件名和内容类型
// Add headers to describe file
let headers = {
'Content-disposition': 'attachment; filename="' + 'giraffe.jpg' + '"',
'Content-Type': 'image/png'
};
// Streams are supported for reading files.
let remoteReadStream = bucket.file('giraffe.jpg').createReadStream();
// Set the response code & headers and pipe content to response
res.status(200).set(headers);
remoteReadStream.pipe(res);
没有测试过这个,但似乎是答案