简体   繁体   English

在Koa中如何发送生成的文件

[英]How in Koa send generated file

I need to make a pdf file with user content and send it back. 我需要制作一个包含用户内容的pdf文件,然后将其发送回去。 I chose pdfmake , because then can make a tables. 我选择了pdfmake ,因为这样可以制作表格。 I use Koa .js; 我使用Koa .js;

router.post('/pdf', koaBody(), async ctx => {
      const doc = printer.createPdfKitDocument(myFunctionGeneratePDFBody(ctx.request.body));
      doc.pipe(ctx.res, { end: false });
      doc.end();
      ctx.res.writeHead(200, {
        'Content-Type': 'application/pdf',
        "Content-Disposition": "attachment; filename=document.pdf",
      });
      ctx.res.end();
    });

And get an error 并得到一个错误

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
        at write_ (_http_outgoing.js:572:17)
        at ServerResponse.write (_http_outgoing.js:567:10)
        at PDFDocument.ondata (_stream_readable.js:666:20)
        at PDFDocument.emit (events.js:182:13)
        at PDFDocument.EventEmitter.emit (domain.js:442:20)
        at PDFDocument.Readable.read (_stream_readable.js:486:10)
        at flow (_stream_readable.js:922:34)
        at resume_ (_stream_readable.js:904:3)
        at process._tickCallback (internal/process/next_tick.js:63:19)

But save in intermediate file and send its work ... 但是保存在中间文件中并发送其工作...

router.post('/pdf', koaBody(), async ctx => {
  await new Promise((resolve, reject) => {
    const doc = printer.createPdfKitDocument(generatePDF(ctx.request.body));
    doc.pipe(fs.createWriteStream(__dirname + '/document.pdf'));
    doc.end();
    doc.on('error', reject);
    doc.on('end', resolve);
  })
    .then(async () => {
      ctx.res.writeHead(200, {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment; filename=document.pdf',
      });
      const stream = fs.createReadStream(__dirname + '/document.pdf');
      return new Promise((resolve, reject) => {
        stream.pipe(ctx.res, { end: false });
        stream.on('error', reject);
        stream.on('end', resolve);
      });
    });
  ctx.res.end();
});

Avoid using writeHead , see https://koajs.com/#response . 避免使用writeHead ,请参阅https://koajs.com/#response

Do like this: 这样做:

ctx.attachment('file.pdf');
ctx.type =
  'application/pdf';
const stream = fs.createReadStream(`${process.cwd()}/uploads/file.pdf`);
ctx.ok(stream); // from https://github.com/jeffijoe/koa-respond

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM