繁体   English   中英

如果我得到应用程序流的 Axios 响应内容类型,如何保存 PDF 格式文件?

[英]How to save PDF format file if I get the Axios response content-type of application-stream?

我想将一个八位字节流类型的数据保存到一个 pdf 文件中,数据是正确的,因为我试图使用 Postman 的“发送和保存”功能来成功获取和打开 pdf 文件。

但是,一旦我调用 axios 请求并收到服务器的响应,就无法获得正确的 pdf 文件。 拿到pdf文件后,好像文件坏了,我能不能正确打开它。

这是响应的标题:在此处输入图像描述

        axios.create({
        baseURL: link,
        timeout: 60000,
        headers: {
            Authorization: token
        }
    }).post(apiUrl, {
        .
        .
        .
    }).then(res=>{
        var file_data = res["data"];
        var file_type = res["headers"]["content-type"];
        var blob = new Blob([file_data], {type: file_type});
        saveAs(blob, "Test.pdf")
    });

我找到了这个问题的解决方案,看起来文件的大小与原来的不同,我做了以下更改以接收Blob对象形式的数据来解决它。

axios.create({
    baseURL: link,
    timeout: 60000,
    responseType: 'blob'
    headers: {
        Authorization: token
    }
}).post(apiUrl, {
    .
    .
    .
}).then(res=>{
    var file_data = res["data"];
    var file_type = res["headers"]["content-type"];
    saveAs(file_data, "Test.pdf");
});

使用axios下载二进制文件时,需要在请求中指定服务器返回的数据格式。 对于 PDF 文件,通常需要使用“arraybuffer”。

axios.get(
      "https://example.com/example.pdf",
      {
        responseType: "arraybuffer"
      }
    );

根据文档,有效的选项是:

// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
//   browser only: 'blob'
//   default: 'json'

Axios 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM