【问题标题】:Unable to download file as PDF from browser when using LARAVEL AJAX使用 LARAVEL AJAX 时无法从浏览器下载 PDF 格式的文件
【发布时间】:2020-12-29 11:17:48
【问题描述】:

我正在使用这个 ajax 将我的数据从一个视图传递到 laravel 中的 pdf 视图。我可以在 pdf 预览中获取数据,但无法从浏览器下载

                    
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    url:"{{ route('monthlybilling.monthlybill') }}",
                    type:"GET",
                    //dataType:"json",
                    data:{
                        site:site, 
                        startdate:startdate,
                        },
                        xhrFields: {
                    responseType: 'blob' // to avoid binary data being mangled on charset conversion
                },
                success: function(blob, status, xhr) {
                
                    // check for a filename
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) {
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");
                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location.href = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                            }
                        } else {
                            window.location.href = downloadUrl;
                        }

                        // setTimeout(function() {
                        //     URL.revokeObjectURL(downloadUrl);
                        // }, 100); // cleanup
                    }

这是我的控制器:[

 $data = DB::table('weekly_data')
                ->where('site', $request->site)
                ->whereBetween('report_date',[$request->startdate,$request->enddate])
                ->get();
        
        $pdf = App::make('dompdf.wrapper');
        $pdf = PDF::loadView('weeklypdf', compact('data'));
        $pdf ->setPaper('a4','landscape');
        return $pdf->stream('weeklyBillingReport.pdf');

此外,它无法自动保存文件名,如“weeklyBillingReport.pdf”

当我点击“保存”时,它显示“失败 - 网络错误”

【问题讨论】:

  • 这更像是一个包问题,而不是 Laravel。尝试使用它,看看它是否有效。 return $pdf->download('weeklyBillingReport.pdf');
  • @RianZaman return $pdf->download('weeklyBillingReport.pdf'); 不起作用
  • @KamleshPaul 这是在控制器中使用吗??
  • @nunu 它有两个答案你可以检查

标签: laravel pdf download filenames


【解决方案1】:

我是这样做的:

 $license = license::findOrFail($id);
    $data = [
        'license' => $license,
        'user' => Auth::user(),
        'labels' => LicValues::where('license_id', $id)->get()
    ];
    return PDF::loadView('print', $data)->download('print.pdf');

我有一个名为 print 的刀片,我将 $data 传递给它,最后下载它。

还有它的 ajax 请求

【讨论】:

    【解决方案2】:

    解决办法:

       success: function(blob, status, xhr) {
                        var ieEDGE = navigator.userAgent.match('/Edge/g');
                        var ie = navigator.userAgent.match('/.NET/g'); // IE 11+
                        var oldIE = navigator.userAgent.match('/MSIE/g');
    
                        if (ie || oldIE || ieEDGE) {
                            window.navigator.msSaveBlob(blob, fileName);
                        } else {
                            var fileURL = URL.createObjectURL(blob);
                            document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>');
                        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 2021-10-20
      • 2018-05-21
      • 1970-01-01
      • 2014-09-09
      • 2021-01-03
      • 2016-04-03
      • 2019-08-24
      相关资源
      最近更新 更多