根据要求在Firebase中下载文件 [英] Download File on Request in Firebase
本文介绍了根据要求在Firebase中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种解决方案,可以在遇到API端点时直接下载Firebase存储中的文件.我尝试初始化Google-Cloud存储并从存储桶中下载文件.
I am looking for a solution to directly download a file in the Firebase Storage when hitting an API endpoint. I tried initializing a Google-Cloud Storage and downloading the file from the bucket.
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
有人可以帮我吗?
推荐答案
如果打算将文件流传输到发出请求的客户端,则可以将数据从Cloud Storage传递到响应.它将类似于以下内容:
If the intention is to stream the file to the requesting client, you can pipe the data from Cloud Storage through to the response. It will look similar to the following:
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);
这篇关于根据要求在Firebase中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文