通过 API node.js 下载并保存 PDF 文件

问题描述 投票:0回答:1

我在从 API 下载文件并正确保存时遇到问题。 这是我的代码:

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 中设置编码,但仍然几乎相同。

有人对如何正确保存 PDF 文件有一些建议吗?

非常感谢!!

如果编码有问题,我尝试了这个,但仍然是同样的问题:

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

还有

fs.writeFileSync(pdfFileName, pdfData),{ 编码:“base64”, };

node.js jspdf
1个回答
0
投票

请使用此代码:

axios({
  method: 'get',
  url: apiUrl,
  responseType: 'stream', // Set the response type to 'stream' to handle 
  binary data
 }).then((response) => {
    const pdfStream = fs.createWriteStream(downloadPath);
    response.data.pipe(pdfStream);
    pdfStream.on('finish', () => {
      console.log('PDF file downloaded successfully.');
    });

  pdfStream.on('error', (err) => {
     console.error('Error downloading PDF:', err);
   });
   }).catch((error) => {
   console.error('Error making the API request:', error);
 });
© www.soinside.com 2019 - 2024. All rights reserved.