【问题标题】:Firebase Cloud Function Serving Local File for DownloadFirebase 云函数服务本地文件以供下载
【发布时间】:2019-08-11 03:18:03
【问题描述】:

我创建了生成 xlsx 文件的云函数,我需要用户在生成该文件后下载该文件。

方法一:上传到Bucket,然后重定向

到目前为止,我已经尝试使用此 API 将文件上传到存储桶,然后将他重定向到存储桶文件 url,我还使用此 API 仔细检查了存储桶名称,但我得到了同样的错误每次:

{"error":{"code":500,"status":"INTERNAL","message":"function crashed","errors":["socket hang up"]}}

包含上传到bucket的部分代码:

    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,所以它无法控制服务器。

【问题讨论】:

  • 能否请您提供用于将文件上传到云存储的代码以及显示您“读取文件”的位置以及您尝试从云函数返回什么的代码.
  • @DennisAlund 我添加了代码
  • 我刚刚注意到您在问题中说的是 XML,但文件后缀是 XLSX。你是说 XML 吗?
  • 对不起,我搞错了,是xlsx

标签: node.js firebase download google-cloud-platform google-cloud-functions


【解决方案1】:

只是想为答案添加更多细节,因为无需写入文件并从中读取以下载数据,只需使用以下几行获取数据并发送即可。

    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    res.end(fileData, 'binary');

【讨论】:

  • 不要忘记对你的文件名进行 url 编码,否则如果文件名超出 ascii,你会得到一些错误:res.setHeader('Content-Disposition', `${contentDisposition}; filename*=utf-8''${encodeURIComponent(fileName)}`);
【解决方案2】:

如果您的 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);

【讨论】:

  • 第一个没有上传到存储桶的解决方案有效,非常感谢。
  • 很高兴听到这个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 2020-01-28
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
  • 2017-01-13
  • 2011-01-03
相关资源
最近更新 更多