[英]Firebase Cloud Function Serving Local File for Download
我创建了生成 xlsx 文件的云函数,我需要用户在生成后下载该文件。
到目前为止,我已经尝试使用此API将文件上传到存储桶,然后将他重定向到存储桶文件 url,我还使用此API仔细检查了存储桶名称,但每次都遇到相同的错误:
{"error":{"code":500,"status":"INTERNAL","message":"function crashed","errors":["socket hang up"]}}
包含上传到存储桶的代码部分:
const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
await storage.bucket('bucket-name').upload('myfile.xlsx', {
gzip: false,
});
证明文件存在的代码部分:
fs.access('myfile.xlsx', fs.constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
我还检查了库“@google-cloud/storage”是否读取了该文件,它是否正确读取并获取了正确的文件大小。
直接下载文件,问题是nodejs下载本地文件给用户的每个在线文档都在设置自定义服务器来下载文件,但我使用的是firebase,所以它不受该服务器的控制。
如果您的 excel 文件已创建并且应该作为对 HTTP 请求(调用 API 端点)的响应返回给客户端,那么您可以这样做。
export const getExcelFile = functions.https.onRequest(async (request, response) => {
// ...
// Create your file and such
// ..
await storage.bucket('bucket-name').upload('myfile.xlsx', {
gzip: false,
});
response.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
response.send(fs.readFileSync('myfile.xlsx'));
return null;
});
否则,如果创建 excel 文件作为对事件的响应,并且您希望用户在其他时间下载该文件,则您可以创建一个下载链接并以您想要的任何方式将其提供给用户。
// ...
// Create your file and such
// ..
const [file] = await storage.bucket('bucket-name').upload('myfile.xlsx', {
gzip: false,
});
const [downloadUrl] = await file.getSignedUrl({
action: 'read',
expires: '20-03-2019' // Link expiry date: DD-MM-YYYY
});
console.log(downloadUrl);
只是想为答案添加更多细节,因为无需写入文件并从中读取以下载其数据,只需使用以下几行获取数据并发送即可。
res.setHeader('Content-Type', 'application/vnd.openxmlformats');
res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
res.end(fileData, 'binary');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.