如何使用云函数中的 response.sendFile 从云存储发送文件?

Dya*_*yan 4 google-cloud-storage firebase google-cloud-functions

我正在尝试使用来自 firebase 云功能的 http 触发器将响应发送回客户端。当我使用 Cloud Storage 中的文件位置发送响应时,sendFile 方法会引发此错误:

"path must be absolute or specify root to res.sendFile"

res.sendFile(obj.path(param1, param2, param3, param4));
Run Code Online (Sandbox Code Playgroud)

obj.path(param1, param2, param3, param4) 这将使用参数构建 gs:// 或 https:// 的路径。

然后我决定这样做:

const rp = require("request-promise");

exports.fun = functions.https.onRequest( async (req, res) => {
let extResponse = await rp('firebase storage location');
          extResponse.pipe(res);
});
Run Code Online (Sandbox Code Playgroud)

rp 现在返回此错误:

StatusCodeError: 403 - "{\n  \"error\": {\n    \"code\": 403,\n    \"message\": \"Permission denied. Could not perform this operation\"\n  }\n}"
Run Code Online (Sandbox Code Playgroud)

此错误是因为云存储需要对请求进行身份验证才能让服务从存储中下载文件。

有没有办法完成这项工作并将文件返回给客户端?

Dou*_*son 8

sendFile 不起作用,因为它不理解 URL。它只理解本地文件系统上的文件。您应该使用Cloud Storage SDK for node来执行此操作。创建一个指向要发送的文件的File对象,在其上打开一个读取流,然后将该流通过管道传输到响应:

const file = ... // whatever file you want to send
const readStream = file.createReadStream()
readStream.pipe(res)
Run Code Online (Sandbox Code Playgroud)