【发布时间】:2021-09-09 10:15:34
【问题描述】:
我正在使用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;
});
}
},
【问题讨论】:
-
我不确定 vuejs 但是这个 axios 可以工作 axios({ url: 'localhost:8002/test', method: 'GET', responseType: 'blob', }).then((response) = > { var fileURL = window.URL.createObjectURL(new Blob([response.data])); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'file .pdf'); document.body.appendChild(fileLink); fileLink.click(); });
-
@JohnLobo:还是不行。仅供参考,当我在 Postman (api/staff/staff-management/download-pdf) 中测试我的网址时,它显示为空白。我不知道为什么。但是,如果我使用纯 laravel,上面的代码就可以工作了。
-
现在,我找到了问题所在。无法验证文件。如果我让它免费,任何人都可以下载它。但是,如果我使用中间件和
Auth::user()->token()对文件进行身份验证,则文件显示为空白。为什么?