【问题标题】:Angularjs: how to properly save a blob pdf file recieved from the serverAngularjs:如何正确保存从服务器收到的 blob pdf 文件
【发布时间】:2016-10-24 08:01:44
【问题描述】:

收到的文件通过$http,我需要将响应数据保存到一个文件中,我使用的是angular-file-saver,收到的文件是pdf docx,但是查看保存的pdf文件在阅读器上什么也看不到,而像PostMan 这样的其他下载器确实保存了它。

负责保存的函数有这样的代码:

function saveFile(data, header){
    var extensions = {
        "application/pdf": ".pdf",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"
    }

    var file = new Blob([data], {type: header});

    FileSaver.saveAs(file, documentsShow.document.name + extensions[header]);
}

data 是从$http 成功检索到的正文数据,header 是从$http 响应中收到的Content-Type

如果需要,$http 代码如下:

$http({
    method: "GET",
    data: data,    //This is sometimes null but it's not relevant for the application
    url: "path/to/download"
}).then(function(data){
    saveFile(data.data, data.header("Content-Type"));
});

【问题讨论】:

    标签: angularjs pdf


    【解决方案1】:

    我在这里看到的主要问题是 Angular 仍会尝试将响应解析为 JSON。

    您可以修改它,使其使用Blob 对象解析

    $http.get('path/to/download', {
        responseType: 'blob'
    }).then(function(res) {
        FileSaver.saveAs(res.data, ...)
    });
    

    仅供参考,data 未在 GET 请求中使用。

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 2016-02-13
      相关资源
      最近更新 更多