我正在尝试从服务器下载一个.pdf文件(意思是在服务器上创建一个文件实例),该文件以二进制格式以二进制格式返回:Content-Type = application / octet-stream。
经过一段时间的在线研究,我写到:
http.get(url.parse(pdfURL), res => {
let data = [];
console.log(res.statusCode);
res.on('data', chunk => {
data.push(chunk);
}).on('end', () => {
let buffer = Buffer.concat(data);
console.log(buffer.toString('base64'));
fs.open(path, 'w', (e, fd) => {
if (e) throw e;
fs.write(fd, buffer, 0, buffer.length, null, e => {
if (e) throw e;
fs.close(fd, () => console.log('Wrote successfully'));
});
});
});
});一切正常工作,但当我试图打开生成的pdf,它告诉我,文件是损坏和不可读的。知道有什么不对劲吗?
谢谢
编辑:我注意到邮递员一切正常工作,所以我认为我对待二进制文件的方式是错误的。
发布于 2019-11-16 18:29:37
好的,我明白了,我没有把反应拉链,现在正常工作了
发布于 2020-11-03 16:36:42
这对我没有用,尝试了很多不同的方法,直到我找到了got,一个处理http请求的npm库,下面是对我有用的方法:
const stream = require('stream');
const { promisify } = require('util');
const fs = require('fs');
const got = require('got');
const pipeline = promisify(stream.pipeline);
async function downloadImage(url, name) {
await pipeline(
got.stream(url),
fs.createWriteStream(name)
);
}更多信息在这里:https://bleext.com/post/downloading-images-with-nodejs
https://stackoverflow.com/questions/58867243
复制相似问题