javascript 使用 nodejs aws sdk 将生成的 pdf 上传到 AWS S3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34257185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:27:20  来源:igfitidea点击:

Upload pdf generated to AWS S3 using nodejs aws sdk

javascriptnode.jsamazon-s3aws-sdknode-pdfkit

提问by Shivendra Soni

I am using pdfkit to generate a pdf with some custom content and then sending it to an AWS S3 bucket.

我正在使用 pdfkit 生成带有一些自定义内容的 pdf,然后将其发送到 AWS S3 存储桶。

While if I generate the file as a whole and upload it works perfectly, however, if I want to stream the generated file probably as an octet stream I am not able to find any relevant pointers.

虽然如果我将文件作为一个整体生成并上传它可以完美运行,但是,如果我想将生成的文件作为八位字节流进行流式传输,我将无法找到任何相关的指针。

I am looking for a nodejs solution (or suggestion).

我正在寻找 nodejs 解决方案(或建议)。

回答by Shivendra Soni

I'll try to be precise here. I will not be covering usage of pdfKit's nodejs sdk in much detail.

我会在这里尽量准确。我不会详细介绍pdfKit的 nodejs sdk 的使用。

IF you want your generated pdf as a file.

如果您希望将生成的 pdf 作为文件。

var PDFDocument = require('pdfkit');

// Create a document
doc = new PDFDocument();

// Pipe it's output somewhere, like to a file or HTTP response
doc.pipe(fs.createWriteStream('output.pdf'));
doc.text('Whatever content goes here');
doc.end();
var params = {
  key : fileName,
  body : './output.pdf',
  bucket : 'bucketName',
  contentType : 'application/pdf'
}

s3.putObject(params, function(err, response) {

});

However if you want to stream it ( to say S3 bucket in the context of question), then it is worth remembering that every pdfkit instance is a readable stream.

但是,如果您想流式传输它(在问题的上下文中说 S3 存储桶),那么值得记住的是,每个 pdfkit 实例都是一个可读的流。

And S3 expects a file, a buffer or a readable stream. So,

S3 需要一个文件、一个缓冲区或一个可读流。所以,

var doc = new PDFDocument();

// Pipe it's output somewhere, like to a file or HTTP response
doc.text("Text for your PDF");
doc.end();

var params = {
  key : fileName,
  body : doc,
  bucket : 'bucketName',
  contentType : 'application/pdf'
}

//notice use of the upload function, not the putObject function
s3.upload(params, function(err, response) {

});