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

Laravel 8 API与Vue.js下载PDF文件为空问题求助

解决Laravel API + Vue.js下载PDF空白问题

问题分析

空白PDF的核心原因是后端响应头设置错误和前端请求参数位置不对,从控制台输出的PDF内容来看,文件本身是正常的。

修复步骤

1. 修正Laravel API代码

后端无需在响应头里设置responseType,这是前端请求的参数,直接返回文件即可:

public function download_invoice(Request $request)
{
    $invoice_id = $request->input('invoice_id');
    $path = public_path('images/pdf').'/'.$invoice_id.'.pdf';
    
    // 先校验文件是否存在,避免报错
    if (!file_exists($path)) {
        return response()->json(['error' => '文件不存在'], 404);
    }
    
    // Laravel的download方法会自动处理正确的响应头
    return response()->download($path, $invoice_id.'.pdf');
}

2. 修正Vue.js请求代码

responseType是请求的顶级配置项,不能放在headers里,同时无需二次包裹Blob:

downloadInvoice(item){
    this.$http.post('downloadinvoice', item, {
        headers: {
            Authorization: `Bearer ${this.token}`
        },
        responseType: 'blob' // 移到顶级配置,而非headers子项
    })
    .then(res=> {
        const fileName = item.invoice_id + '.pdf';
        const url = window.URL.createObjectURL(res.data); // res.data已是Blob对象
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        // 清理资源,避免内存泄漏
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
    })
    .catch(err => {
        console.error('下载失败:', err);
    })
}

关键说明

  • 后端:response()->download会自动设置Content-Type: application/pdf和Content-Disposition响应头,无需手动添加无关配置。
  • 前端:responseType属于axios(假设$http是axios封装)的请求配置参数,必须放在顶级配置中;当设置为blob时,响应数据已经是Blob类型,不需要再用new Blob()包裹。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:45:04