laravel - Laravel DomPDF 使用 Axios 时获取空白文件
问题描述
我正在使用https://github.com/barryvdh/laravel-dompdf、Axios 和 Vuejs 来生成 PDF 文件。是的,我可以下载文件,但是文件是空白的,文件大小是 0 字节。为什么会发生这种情况?
控制器
public function downloadPDF()
{
$staffs = Staff::all();
$pdf = PDF::loadview('staffs.pdf', ['staffs' => $staffs]);
return $pdf->output();
}
PDF 查看
<table class='table table-bordered'>
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@php $i=1 @endphp
@foreach ($staffs as $staff)
<tr>
<td>{{ $i++ }}</td>
<td>{{ $staff->name }}</td>
<td>{{ $staff->email }}</td>
</tr>
@endforeach
</tbody>
</table>
路线
Route::get('staff-management/download-pdf', [StaffController::class, 'downloadPDF'])->name('staff.pdf');
看法
exportFiles() {
this.loading = true;
if ($('.export-files').val() == 'PDF') {
this.axios
.get('api/staff/staff-management/download-pdf', {
responseType: 'blob',
Accept: 'application/pdf',
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/pdf'}));
const link = document.createElement('a');
console.log(link);
link.href = url;
link.setAttribute('download', 'staffs.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((error) => {
console.log(error);
})
.finally(() => {
this.loading = false;
});
}
},
解决方案
问题是axios
将从服务器收到的每个响应视为blob
使用 JavaScript 创建的 pdf。为了避免在服务器发送状态中发送响应时也发生这种情况。例如
return [
'status'=>"success",
"data"=> mb_convert_encoding($pdf->output(), 'UTF-8', 'UTF-8')
];
然后在 axios
exportFiles() {
this.loading = true;
if ($('.export-files').val() == 'PDF') {
this.axios
.get('api/staff/staff-management/download-pdf', {
Accept: 'application/pdf',
})
.then((response) => {
if(response.data.status=="success") {
const url = window.URL.createObjectURL(new Blob([response.data.data], {type: 'application/pdf'}));
const link = document.createElement('a');
console.log(link);
link.href = url;
link.setAttribute('download', 'staffs.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
} else{
alert("Not Authenticated");
}
})
.catch((error) => {
console.log(error);
})
.finally(() => {
this.loading = false;
});
}
},
如果用户未通过身份验证,其他方式是从 200 以外的服务器发送状态。因此您可以在 axios 错误处理中处理它
如果不显示下载 pdf 按钮,则首先检查用户是否已登录的另一种方法。
推荐阅读
- c# - 如何以另一种形式访问控制(按钮)[C#]
- laravel - 背包 laravel 如何在同一个视图中显示相关表
- javascript - 如何添加错误处理以检查输入是否是单独函数中的数字
- c# - 如何通过c#将用户控件从另一个用户控件带到前面
- php - 用于登录的标准正确 ajax 响应
- java - Java 嵌套的 while 循环无法按预期运行
- r - rbokeh,将图例添加到直方图
- python - 简化动态列表中字符串的修改?
- android - 如何在mainActivity中设置ExpandableListView的childView
- c++ - 为什么 std::string[] 数组的 size() 函数返回的参数数量不正确