Download binary data from backend to file on frontend

Viewed 2841

I have a Express.js backend that sends in-memory generated *.zip with *.docx files inside it. Zip is sent as a buffer. Backend sends data, frontend receives it. It's all good until that point.

The problem is that when I receive it at the frontend using axios I can't force browser to download it as a *.zip client-side so user can open it and use.

This is what I do on the frontend:

      let formData = new FormData()
      formData.append("data", JSON.stringify(this.data))
      formData.append("template", this.template)

      axios.post('http://localhost:3001/gen', formData, {
        responseType: 'blob',
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(res => {
        res.end( res.data, 'binary' );
      })

but it's not downloading file as I wish. I'm not saving file anywhere on the server - I just create it on the fly in the memory and send it to the client.

1 Answers

On a response from axios you'll need to let the browser handle the download. See e.g. https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743 or https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

In your case it should be something like:

let formData = new FormData()
formData.append("data", JSON.stringify(this.data))
formData.append("template", this.template)

axios.post('http://localhost:3001/gen', formData, {
    responseType: 'blob',
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})
.then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'some_file_name.ext');
    document.body.appendChild(link);
    link.click();
    link.remove();
})

Note that it might not work in some cases, e.g. Internet Explorer. Check out https://github.com/kennethjiang/js-file-download if you need support for that.

Related