我正在尝试从 API 获取文档(pdf/docx/zip/..)并将其与在响应标头中的内容处置处收到的文件名一起保存。我尝试了以下方法。但是文件未使用实际文件名保存,或者文件使用损坏的(0kb)文件保存。我已经尝试了 2 天了。有人能指出哪里出了问题吗?
var calloptions = {
method: 'GET',
url: 'https://ip:port/address',
qs: { docId: 'something toffetch' },
headers:
{
'content-type': 'application/json',
authorization: postData.bcAccessToken
}
};
console.log("calloptions", calloptions);
var filepath = require('path').join(require('os').homedir(), 'Desktop');
var name = 123;
var myFile = [];
request(calloptions, function (error, response, body) {
if (error) throw new Error(error);
var chunks = [];
name = 456;
// var myFile ;
//original=;
console.log(response.headers["content-disposition"]);
if (response.headers["content-disposition"]) {
myFile.push(filepath + "\\" + response.headers["content-disposition"].split("=").pop());
console.log(myFile);
// console.log(myFile);
console.log("BEFORE WRITTING");
response.on('data', function (chunk) {
while (chunk = this.read()) {
chunks.push(chunk);
//chunk.pipe(fs.appendFile(filepath+"\\"+response.headers["content-disposition"].split("=").pop()));
}
// fs.appendFileSync(myFile, chunk);
// fs.appendFile(myFile, chunk, function (err) {
// if(err) throw err;
// console.log("DURING WRITTING");
// console.log("myFile :- ",myFile);
// });
//chunks.pipe(fs.appendFile(filepath+"\\"+response.headers["content-disposition"].split("=").pop()));
// console.log("writing completed to file");
});//.pipe(fs.createWriteStream(filepath+"\\"+response.headers["content-disposition"].split("=").pop()));
console.log("AFTER WRITTING");
}
}).on('end', () => {
console.log('There will be no more data.');
console.log("IN THE END - ");
console.log(name);
console.log(myFile);
});//.pipe(fs.createWriteStream(filepath+"\\"+name));
console.log("AFTER REQUEST");