BGeorge
BGeorge

Reputation: 139

Download file on the browser

I am trying to get the file downloaded at the user browser. I am using azure-storage SDK. Following is the express code. I can see the files being retrieved on the browser console. But it just is not prompting a download for the user. enter image description here

app.get('/download', (req, res) => {
  res.attachment(req.get('blobName'));
  blobService.getBlobToStream(req.get('container'), req.get('blobName'), res, function (error, result, response) {
    console.log(error);
    console.log(result);
    console.log(response);
  });
});

Upvotes: 2

Views: 3592

Answers (2)

Jerry Liu
Jerry Liu

Reputation: 17790

Request succeeds so problem is not related to express code.

You seem to use XMLHttpRequest to send request.

XMLHttpRequest gets the file content in response, but it doesn't download the file as an attachment automatically.

We have to add some code to make file downloaded by browser.

...
//set type to blob, so that response can be used in createObjectURL method
xhr.responseType = "blob";
xhr.send();

xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var downloadUrl = URL.createObjectURL(xhr.response)
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = downloadUrl;
        a.download = blobname;
        a.click();
}};

Upvotes: 1

miqe
miqe

Reputation: 3369

you could try to using response header so that the browser download the file instead of treating it as the typical response.

res.setHeader('Content-disposition', 'attachment; filename=' + blobname);
res.setHeader('Content-type', 'application/pdf');

for further reference you could refer to Mozilla developer's site about Content-disposition

Upvotes: 0

Related Questions