0

我正在尝试从 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");                      
4

1 回答 1

0

我通过使用 async.waterfall 解决了它,如下所示。但总是赞赏解决此问题的更好方法。

async.waterfall([
     function (callback) {
         request(calloptions, function (error, response, body) {
             if (error) throw new Error(error);
             console.log(response.headers["content-disposition"]);
             if (response.headers["content-disposition"]) {

                 //var myFile2 = filepath + "\\" + response.headers["content-disposition"].split("=").pop();
                 var body = '';
                 response.on('data', function (chunk) {
                     body += chunk;
                 });
                 callback(null, response.headers["content-disposition"].split("=").pop());
             }
         }).pipe(fs.createWriteStream(filepath+"\\"+"Orig.pdf"));
     },
     function (res, callback) {
         console.log("SECOND FUNCTION");
         console.log(res);
         fs.rename(filepath+"\\"+"Orig.pdf", filepath+"\\"+res, function (err) {
             if (err) throw err;
             console.log('renamed complete');
           });
     }
 ])
于 2018-12-20T10:26:16.230 回答