请求-承诺下载pdf文件 [英] request-promise download pdf file
问题描述
我收到了多个pdf文件,必须从REST-API下载.
I received multiple pdf files and must download it from a REST-API.
经过身份验证并连接后,我尝试下载带有请求承诺的文件:
After auth and connect I try to download the file with request-promise:
const optionsStart = {
uri: url,
method: 'GET',
headers: {
'X-TOKEN': authToken,
'Content-type': 'applcation/pdf'
}
}
request(optionsStart)
.then(function(body, data) {
let writeStream = fs.createWriteStream(uuid+'_obj.pdf');
console.log(body)
writeStream.write(body, 'binary');
writeStream.on('finish', () => {
console.log('wrote all data to file');
});
writeStream.end();
})
该请求创建了一个pdf文件(大约1-2MB),但我无法打开它. (Mac预览显示空白页,而Adobe显示=>
The request create a pdf (approximately 1-2MB) but I can't open it. (Mac Preview show blank pages and adobe show = >
打开此文档时出错.阅读时出现问题 该文档(14).
There was an error opening this document. There was a problem reading this document (14).
我没有下载文件所在的API端点的信息.保持卷曲:
I have no information about the API Endpoint where I download the files. Just have this curl:
curl -o doc.pdf --header "X-TOKEN: XXXXXX"
http://XXX.XXX/XXX/docs/doc1
我的错误在哪里?
更新:
我在编辑中打开了文件,文件看起来像这样:
I opened the file in edit and the file looks like that:
没有任何经验:-)
推荐答案
在您的请求选项中添加编码:二进制":
Add encoding: 'binary' to your request options:
const optionsStart = {
uri: url,
method: "GET",
encoding: "binary", // it also works with encoding: null
headers: {
"Content-type": "application/pdf"
}
};
这篇关于请求-承诺下载pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!