MIME二进制数据到PDF

时间:2017-03-28 15:03:35

标签: node.js aws-lambda mime

我从API调用中收到一些返回一些XML和相关文件(PDF)的数据:

var req = http.request(HTTPOPTIONS, function(resp){
var rawData = '';
//Build list from response data
resp.on('data', function (chunk) {
    rawData+= chunk;
});
//Process List
resp.on('end', function () {
        var breakStr = rawData.split('\n')[0];
        var fileSections = rawData.split(breakStr);
        for(var i in fileSections){
            var content = fileSections[i].split((/Content-Length: [0-9]*/));
            var fileName = content[0].split('filename=')[1].trim();
            var file = {Bucket : 'MyBucket', Key: ROOT+'/'+FOLDER+'/'+SUBFOLDER+'/'+fileName, Body: content[1]};
            console.log('Creating file: '+file.Key );
            promises.push(S3.upload(file).promise());
        }
        Promise.all(promises).then(...);
    });
});
req.write(XMLREQUEST);
req.end();

但是当我尝试打开创建的文件时,我得到[an error message saying the file is damaged

关于我哪里出错的任何想法?

更新:

除了上述错误消息,我还得到[an error saying the 'document has been changed'

在这些文件中,我获得了元数据(页面大小/格式和字体数据),但没有内容。

1 个答案:

答案 0 :(得分:1)

看来问题是因为我将数据存储在一个字符串中并试图从那里操纵它。传入数据chunk是一个缓冲区,并以此形式使用它意味着,一旦您弄清楚如何删除标题,就可以创建PDF文件。

var req = http.request(HTTPOPTIONS, function(resp){
var respChunks =[];
var respChunksLength = 0;

resp.on('data', function (chunk) {
    respChunks.push(chunk);
    respChunksLength+=chunk.length;
});

resp.on('end', function () {
    var confResp = Buffer.concat(respChunks, respChunksLength);
    var breakStr = confResp.slice(0,confResp.indexOf('\n'));
    var bufferArray = [];
    var startBreak = confResp.indexOf(breakStr);
    while(startBreak>-1){
        bufferArray.push(confResp.slice(startBreak+breakStr.length+1,confResp.indexOf(breakStr,startBreak+1)));
        startBreak = confResp.indexOf(breakStr,startBreak+1);
    }
    var trim=0;
    for(var i = 1; i<bufferArray.length;i++){
        trim = bufferArray[i].toString().indexOf('%');
        fs.writeFile('testFile'+i+'.pdf',bufferArray[1].slice(trim));
    });
});
req.write(generateProposalDetailXML());
req.end();

bufferArray连接到一个缓冲区中,然后根据MIME分隔符(breakStr)进行划分,并删除标题(笨拙)并将其写入文件。