在浏览器上下载文件

时间:2018-05-25 16:15:12

标签: node.js azure express azure-storage azure-storage-blobs

我正在尝试在用户浏览器下载文件。 我正在使用azure-storage SDK。以下是快递代码。我可以在浏览器控制台上看到正在检索的文件。但它并没有提示用户下载。 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);
  });
});

2 个答案:

答案 0 :(得分:1)

请求成功,因此问题与快速代码无关。

您似乎使用XMLHttpRequest发送请求。

XMLHttpRequest获取文件内容作为响应,但它不会自动将文件作为附件下载。

我们必须添加一些代码才能通过浏览器下载文件。

...
//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();
}};

答案 1 :(得分:0)

您可以尝试使用响应标头,以便浏览器下载文件,而不是将其视为典型响应。

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

有关进一步参考,您可以参考Mozilla开发人员关于Content-disposition

的网站