【问题标题】:How to send a file from cloud storage using response.sendFile in cloud functions?如何在云函数中使用 response.sendFile 从云存储发送文件?
【发布时间】:2019-06-25 04:36:01
【问题描述】:

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

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

res.sendFile(obj.path(param1, param2, param3, param4));

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);
});

rp 现在返回此错误:

StatusCodeError: 403 - "{\n  \"error\": {\n    \"code\": 403,\n    \"message\": \"Permission denied. Could not perform this operation\"\n  }\n}"

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

有没有办法让它工作并将文件返回给客户端?

【问题讨论】:

    标签: firebase google-cloud-storage google-cloud-functions


    【解决方案1】:

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

    const file = ... // whatever file you want to send
    const readStream = file.createReadStream()
    readStream.pipe(res)
    

    【讨论】:

    • 我无法测试您写的内容,但我相信这有助于解决问题。一旦我可以测试它,我就会将其标记为已回答。
    • 我在一个工作项目中做同样的事情。我从其他示例代码中借用了该技术。如果你不正确,它会起作用。
    猜你喜欢
    • 2021-10-21
    • 2021-02-14
    • 2020-10-14
    • 2019-12-23
    • 1970-01-01
    • 2019-10-15
    • 2018-08-18
    • 2017-08-18
    • 2021-04-27
    相关资源
    最近更新 更多