我想使用axios下载pdf文件,并使用fs.writeFile保存在磁盘(服务器端)上,我已经尝试过:

axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => {
    fs.writeFile('/temp/my.pdf', response.data, (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    });
});

文件已保存,但内容已损坏...

如何正确保存文件?

最佳答案

实际上,我相信以前接受的答案存在一些缺陷,因为它不能正确处理写流,因此,如果在Axios给您响应后调用“then()”,最终将得到部分下载的文件。
当下载稍大的文件时,这是一个更合适的解决方案:

export async function downloadFile(fileUrl: string, outputLocationPath: string) {
  const writer = createWriteStream(outputLocationPath);

  return Axios({
    method: 'get',
    url: fileUrl,
    responseType: 'stream',
  }).then(response => {

    //ensure that the user can call `then()` only when the file has
    //been downloaded entirely.

    return new Promise((resolve, reject) => {
      response.data.pipe(writer);
      let error = null;
      writer.on('error', err => {
        error = err;
        writer.close();
        reject(err);
      });
      writer.on('close', () => {
        if (!error) {
          resolve(true);
        }
        //no need to call the reject here, as it will have been called in the
        //'error' stream;
      });
    });
  });
}
这样,您可以调用downloadFile(),对返回的promise调用then(),并确保下载的文件已完成处理。

07-24 09:46
查看更多