我用 Laravel 创建了一个 API。我在前端使用 Vuejs。
我想根据用户生成 PDF 并下载并查看。只是,它不起作用。
这是我的 Controller :
public function generate($id)
{
$data = CoverLetter::where([
['id', '=', $id],
['user_id', '=', auth()->user()->id]
])->first();
$path = public_path() . '/pdf/' . $data->filename . '.pdf';
$pdf = PDF::loadView('pdf.coverletter', $data);
$pdf->save($path);
return response()->download($path);
}
还有我在 vue 中的功能:
async downloadCoverLetter(file) {
axios.get('/cover-letter/generate/' + file.id)
}
还有我的下载按钮:
<button @click="downloadCoverLetter(file)"></button>
但它根本不下载。怎么做 ?谢谢!
最佳答案
您可以尝试使用以下代码使用 Axios 下载文件:
axios({
url: '/cover-letter/generate/' + file.id,
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});
关于laravel - 使用 laravel-dompdf 和 vuejs 前端下载 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57649147/