微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Firebase 中按请求下载文件

如何解决在 Firebase 中按请求下载文件

我正在寻找一种解决方案,以便在访问 API 端点时直接下载 Firebase 存储中的文件。我尝试初始化 Google-Cloud Storage 并从存储桶中下载文件

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

const storage = new Storage({keyFilename: keyPath});

app.get("/download",(req,res) => {
    storage.bucket(bucketName).file("file.txt").download({destination: './file.txt'});
});

app.listen(8080);

但这不起作用!

我只是明白:

UnhandledPromiseRejectionWarning: Error: Not Found

有人可以帮我吗?

解决方法

您在哪里初始化 app

原答案:

// Dependencies
const express = require('express')

const PORT = process.env.PORT || 3002;

// Initialize the App
const app = express();

// Start the app
app.listen(PORT,() => {
    console.info(`Server is listening on port ${PORT}`);
});

更新: 发出下载文件的 HTTP 请求是一种异步操作。您需要等待文件从 Google Cloud Storage 下载,然后再发送给客户端

const app = require('express')();
const { Storage } = require("@google-cloud/storage");
const storage = new Storage({keyFilename: keyPath});

// I am using async/await here
app.get("/download",async (req,res) => {

// You have to wait till the file is downloaded
    await storage.bucket(bucketName).file("file.txt").download({destination: './file.txt'});
// Send the file to the client
res.download('./file.txt')
});

app.listen(8080);
,

如果打算将文件流式传输到发出请求的客户端,您可以通过管道将数据从 Cloud Storage 传送到响应。它将类似于以下内容:

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

const BUCKET_NAME = 'my-bucket';

const app = express();
const storage = new Storage({keyFilename: './path/to/service/key.json'});

app.get("/download",(req,res) => {
    storage.bucket(bucketName).file("path/in/bucket/to/file.txt").createReadStream()
      .on('error',(err) => {
        res.status(500).send('Internal Server Error');
        console.log(err);
      })
      .on('response',(storageResponse) => {
        // make sure to check storageResponse.status

        res.setHeader('content-type',storageResponse.headers['Content-Type']);
        res.setHeader('content-length',storageResponse.headers['Content-Length']);
        res.status(storageResponse.status);
        // other headers may be necessary

        // if status != 200,make sure to end the response as appropriate. (as it won't reach the below 'end' event)
      })
      .on('end',() => {
        console.log('Piped file successfully.');
        res.end();
      }).pipe(res);
});

app.listen(8080);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。