2016-07-25 291 views
0

我设法让我生成的pdf从我的节点JS服务器上传到s3。 PDF在我的本地文件夹上看起来不错,但是当我试图从AWS控制台访问它时,它表示“加载PDF文档失败”。PDF上传到AWS S3损坏

我已经尝试通过s3.upload和s3.putObject API上传它(对于putObject,我还使用了.on完成检查器以确保文件在发送请求之前已完全加载)。但S3存储区中的文件仍然是相同(小)大小,26个字节,无法加载。任何帮助是极大的赞赏!!!

var pdfDoc = printer.createPdfKitDocument(inspectionReport); 
    var writeStream = fs.createWriteStream('pdfs/inspectionReport.pdf'); 
    pdfDoc.pipe(writeStream); 
    pdfDoc.end(); 
    writeStream.on('finish', function(){ 
     const s3 = new aws.S3(); 
     aws.config.loadFromPath('./modules/awsconfig.json'); 

    var s3Params = { 
     Bucket: S3_BUCKET, 
     Key: 'insp_report_test.pdf', 
     Body: '/pdf/inspectionReport.pdf', 
     Expires: 60, 
     ContentType: 'application/pdf' 
    }; 
    s3.putObject(s3Params, function(err,res){ 
     if(err) 
      console.log(err); 
     else 
      console.log(res); 
    }) 
+2

打开一个文本编辑器中的文件,看看有什么消息 - 最有可能它告诉你关于我接受这份文件应该是超过26个字节的错误 –

+0

。代码中的'console.log(res);'行是否执行并打印任何内容?这听起来像你的应用程序在s3.putObject()调用完成之前退出。 –

+0

'Body:'/ pdf/inspectionReport.pdf','* string /'/ pdf/inspectionReport.pdf'中有多少字节?看起来像26.'身体'期待*身体* - 不是路径。 –

回答

1

我意识到pdfDoc.end()必须在管道启动之前。还使用了回调来确保在pdf写入完成后调用s3上传。看到下面的代码,希望它有帮助!

var pdfDoc = printer.createPdfKitDocument(inspectionReport); 
pdfDoc.end();  

async.parallel([ 

     function(callback){ 
      var writeStream = fs.createWriteStream('pdfs/inspectionReport.pdf'); 
      pdfDoc.pipe(writeStream); 
      console.log('pdf write finished!'); 
      callback(); 
     } 

    ], function(err){ 

     const s3 = new aws.S3(); 
     var s3Params = { 
      Bucket: S3_BUCKET, 
      Key: 'insp_report_test.pdf', 
      Body: pdfDoc, 
      Expires: 60, 
      ContentType: 'application/pdf' 
     }; 

     s3.upload(s3Params, function(err,result){ 
      if(err) console.log(err); 
      else console.log(result); 
     }); 
    } 
);