【问题标题】:Download file on the browser在浏览器上下载文件
【发布时间】:2018-11-05 02:12:32
【问题描述】:

我正在尝试在用户浏览器上下载文件。 我正在使用 azure-storage SDK。以下是快递代码。我可以在浏览器控制台上看到正在检索的文件。但它只是没有提示用户下载。

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);
  });
});

【问题讨论】:

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


【解决方案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();
}};

【讨论】:

    【解决方案2】:

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

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

    如需进一步参考,您可以参考 Mozilla 开发者网站关于 Content-disposition

    【讨论】:

    • 从上面的图片可以看出,这已经在标题中设置了
    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 2019-07-19
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多