You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js通过API下载保存PDF失败,求正确实现方案

问题:Node.js通过API下载PDF后保存乱码、文件为空的问题

我在使用Node.js通过API下载并保存PDF文件时遇到了问题,代码如下:

const axios = require('axios');
const fs = require('fs');

const config = {
    auth: {
     username: //username,
     password: //password,
    },
    headers : {
        Accept: 'application/pdf',
      }
};

const apiUrl = //api URL;

const pdfFileName = 'getPDF.pdf';

axios.get(apiUrl, config)
.then(response => {
  const pdfData = Buffer.from(response.data);
  fs.writeFileSync(pdfFileName, pdfData);
  console.log(`PDF was downloaded and saved correctly ${pdfFileName}`);
})
.catch(error => {
  console.error('Error in download a PDF:', error);
});

执行后返回乱码内容:

��)�������
����_�^���������_�Lfߌ>���S�����?�>-�V���ħA������]2��������?��/��7����W����W������?��k��g�[����?��_�%����(��
����
����5�,����~�5�
�����+| ����'����������_���M�g���k�����������������?��!q����э���ǟ�T�.?�]�1��ٟ����
���� _����
��F5��3��AQ����u��ƿ�fc���
�_�(����.����l��y��G�B������͙��?� ��~�����\���c_��?���D�
��_��k�6g�<�肯����?��!q����э���ǟ�TW��Q@�E���B��(���͙���� ���?�_����ػ�
��V~��G���Z��k�

生成的PDF文件为空。我尝试过在Buffer.from中设置编码:

const pdfData = Buffer.from(response.data, "base64");

也尝试过修改fs.writeFileSync的编码参数:

fs.writeFileSync(pdfFileName, pdfData), {
    encoding: "base64",
};

但问题都没解决,请问如何正确保存PDF文件?


解决方法

问题核心是axios默认会将响应数据解析为字符串,而PDF属于二进制文件,字符串解析会破坏原始二进制数据,导致乱码或空文件。解决的关键是让axios返回原始二进制数据:

  • 添加responseType: 'arraybuffer'配置
    在请求的config中加入该参数,让axios直接返回二进制的ArrayBuffer,避免自动解析为字符串:

    const config = {
        auth: {
         username: //username,
         password: //password,
        },
        headers : {
            Accept: 'application/pdf',
        },
        responseType: 'arraybuffer' // 关键配置,确保返回二进制数据
    };
    
  • 直接写入二进制数据
    此时response.data是ArrayBuffer类型,可直接转为Buffer后写入文件(Node.js也支持直接写入ArrayBuffer):

    axios.get(apiUrl, config)
    .then(response => {
      const pdfBuffer = Buffer.from(response.data);
      fs.writeFileSync(pdfFileName, pdfBuffer);
      console.log(`PDF已成功保存到 ${pdfFileName}`);
    })
    .catch(error => {
      console.error('下载PDF出错:', error);
    });
    
  • 特殊情况:API返回base64编码的PDF
    若确认API返回的是base64格式的字符串,可先解码再写入:

    axios.get(apiUrl, config)
    .then(response => {
      const pdfBuffer = Buffer.from(response.data, 'base64');
      fs.writeFileSync(pdfFileName, pdfBuffer);
    });
    

    注意:只有明确API返回base64时才用此方法,否则不要随意添加base64解码。


内容的提问来源于stack exchange,提问作者jakub.krejcir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:13:17