NodeJS字符串转换为缓冲区PDF文件

3

大家好,我正在尝试下载一个PDF文件并将其保存在我的磁盘上。API发送给我一个字符串。但是下面的代码不起作用。

axios.get('https://myapi.com/download', config).then((res) => {
  var buff = Buffer.from(res.data, 'binary');
  fs.writeFile('file.pdf', buff, function (err) {
    if (err) throw err;
    console.log('Saved!');
  });
}).catch((e) => {
  console.log(e);
})

我已经尝试过它,可行...
fs.readFile('./download.pdf','binary', function (err, data) {
  var str = data.toString();
  var buff = Buffer.from(str, 'binary');
  fs.writeFile('novopdf.pdf',buff, () => {
    console.log('ok');
  })
});

你能详细说明你遇到的问题是什么吗? - Saurabh Ghewari
当我从API保存PDF时,它保存的是一个空文档。 - user10007083
1个回答

2
您需要将axios的get请求配置如下:
const response = await Axios({
 method: 'GET',
 url: url,
 responseType: 'stream'
})

response.data.pipe(Fs.createWriteStream(path)) // path is location where you want to write the file.

然后在响应对象上检查结束事件。

如果您对答案满意,请为答案点赞。 - Saurabh Ghewari
谢谢!对于PDF文件有效。您还可以将此流作为主体传递到另一个HTTP请求中,以将其发送到其他地方(在我的情况下,我必须将此流发送到不同的Web服务器)。 - Ruslan Plastun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接