下载返回的空文件 [英] Download returning empty file

查看:57
本文介绍了下载返回的空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个node.js + express应用程序,用户将在其中输入一些数据,并使用

I'm building a node.js+express application in which the user will input some data, the generates a PDF with pdfkit and the file is sent to the user. I'm being able to generate the file successfully, the problem is that when I download the file generated, it's empty. I can't even open the PDF, the reader (Preview, native reader in macOS) says that the file is empty. I'm using the following code:

var express = require('express');
var router = express.Router();
var guid = require('guid');
var PDFDocument = require('pdfkit');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/criar', function(req, res, next) {
    var filename = guid.raw()+'.pdf';
    var doc = new PDFDocument();
    doc.pipe(fs.createWriteStream(filename));

    doc.font('fonts/UbuntuMono-R.ttf')
        .fontSize(25)
        .text('Some text with an embedded font!', 100, 100);

    doc.end();

    res.download(filename, 'rifas.pdf', function(err){
        if(!err){
            fs.unlink(filename);
        }
    })
});

module.exports = router;

您是否知道为什么我的下载文件为空,而在服务器中却无法正确生成它们?

Do you have any idea on why my downloaded files are empty, while in the server they're being generated correctly?

谢谢!

推荐答案

您真的需要物理文件吗?如果没有,那么您可以直接流式传输到客户端:

Do you really need the physical file? If not then you can stream directly to the client:

var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/criar', function(req, res, next) {
    var doc = new PDFDocument();
    doc.pipe(res);

    doc.font('fonts/UbuntuMono-R.ttf')
        .fontSize(25)
        .text('Some text with an embedded font!', 100, 100);

    doc.end();

});

module.exports = router;

这篇关于下载返回的空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆