Search code examples
expressgoogle-drive-apiblob

Express JS how to send Blob to client


I am trying to download files from a webapp. The download button does a POST request on my backend that in turn edits files on a Google Drive and exports them. I wish to send those back to the front end with no success so far.

The files exported from the google drive API come as Blobs, here is an example:

{
id: '10i7fTyLEmhovfArrbI_1Kvk-pwWRpwU-QgCWnINSQqQ',
file: Blob {
  [Symbol(type)]: 'application/pdf',
  [Symbol(buffer)]: <Buffer 5 25 50 44 46 2d 31 2e 34 0a 25 20 e2 e3 cf d3 ... 3663411 more bytes>
}

If I try to send just one file Blob as is with:

router.post("/getFiles", async (req, res) => {
 const blob = await file from Google drive
 res.header("Content-Type", "application/pdf");
 res.header("Content-Length", blob.size);
 blob.stream().pipe(res);
}

On the front end I handle the blob like so:

axios.post(address, payload)
  .then(response => {
    const blob = new Blob([response?.data], { type: "application/pdf" })
    resolve(window.URL.createObjectURL(blob));
  })
  .catch(err => reject(err));

The URL opens up the pdf viewer but it's blank and the title is complete gibberish

How is the correct way to send Blobs from Express back end to the web?

SOLUTION:

The fix was to add to the config { responseType: "blob" } to the post request

axios.post(address, payload, { responseType: "blob" })
  .then(response => {
    const blob = new Blob([response?.data], { type: "application/pdf" })
    resolve(window.URL.createObjectURL(blob));
  })
  .catch(err => reject(err));

Solution

  • The fix was to add to the config { responseType: "blob" } to the post request

    axios.post(address, payload, { responseType: "blob" })
      .then(response => {
        const blob = new Blob([response?.data], { type: "application/pdf" })
        resolve(window.URL.createObjectURL(blob));
      })
      .catch(err => reject(err));