如何解决使用 LARAVEL AJAX 时无法从浏览器下载 PDF 文件
我正在使用这个 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”那样自动保存文件名
当我点击“保存”时,它显示“失败 - 网络错误”
解决方法
我是这样做的:
$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请求中
,这里的解决方案:
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>');
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。