簡體   English   中英

Firebase 雲函數服務本地文件以供下載

[英]Firebase Cloud Function Serving Local File for Download

我創建了生成 xlsx 文件的雲函數,我需要用戶在生成后下載該文件。

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

到目前為止,我已經嘗試使用此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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM