简体   繁体   中英

Download or view file using google firebase cloud function

What I'm trying to do:

  1. Generate invoice using a third party lib.
  2. Download/View invoice

My code

let createPdf = functions.https.onRequest(async (request, response) => {

    // more code here 

    if (download == 'true') {
        return response.status(200).download(__dirname + "/docs/" + newFileName, newFileName, (err) => {
            if (err) {
                console.log(err.message);
            } else {
                console.log("Downloaded:", filename)
            }
        })
    } else {
        var options = {
            root: __dirname,
            dotfiles: 'deny',
            headers: {
                'x-timestamp': Date.now(),
                'x-sent': true
            }
        };

        return response.status(200).sendFile("/docs/" + newFileName, options, (err) => {
            if (err) {
                console.log(err);
            } else {
                console.log('Sent:', filename);
            }
        });
    }
});

The error

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

Note: When I return a simple string instead of the file it works.

Use express request and response objects to send a file.

Read this documentation: using_express_request_and_response_objects

And don't forget to use absolute path when using sendFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM