You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js下载手动创建的发票PDF时出现空白的问题求助

排查PDF下载空白问题的几个实用方向
  • 确认文件路径准确性
    在fs.readFile前添加console.log(path.resolve(invoicePath)),打印出文件的绝对路径,手动核对该路径下的PDF是否确实存在且有内容。Node.js的相对路径依赖进程启动目录,如果服务不是从项目根目录启动,path.join生成的路径可能指向错误的空文件。

  • 修复Content-Disposition头格式
    代码中用了HTML实体"转义引号,HTTP响应头里直接用双引号即可,错误的转义会导致浏览器解析异常:

    res.setHeader(
        'Content-Disposition',
        `attachment; filename="${invoiceName}"`
    );
    
  • 修正文件读取编码
    fs.readFile默认用utf8编码读取,会破坏PDF二进制文件结构,必须指定encoding: null来读取原始二进制数据:

    fs.readFile(invoicePath, { encoding: null }, (err, data) => {
        if (err) {
            return next(err);
        }
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader(
            'Content-Disposition',
            `attachment; filename="${invoiceName}"`
        );
        res.send(data);
    }); 
    
  • 改用Express原生文件发送方法
    替换手动读取+发送的逻辑,用res.sendFile自动处理文件流和响应头,避免编码或数据截断问题:

    exports.getInvoice = (req, res, next) => {
        const orderId = req.params.orderId;
        const invoiceName = 'invoice-' + orderId + '.pdf';
        const invoicePath = path.join('data', 'invoices', invoiceName);
        res.setHeader('Content-Disposition', `attachment; filename="${invoiceName}"`);
        res.sendFile(invoicePath, (err) => {
            err && next(err);
        });
    };
    
  • 验证读取到的数据
    在res.send(data)前添加console.log(data.length),如果输出为0,说明读取的文件本身为空;如果有正常文件大小,问题则出在响应头或数据发送环节。

内容的提问来源于stack exchange,提问作者user20671017

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:15:56