问题:使用 laravel-dompdf 下载 PDF 和 vuejs 前端

我用 Laravel 创建了一个 API。我在前端使用 Vuejs。

我想根据用户生成PDF并下载查看。只是,它不起作用。

这是我的控制器:

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();
});
Logo

前往低代码交流专区

更多推荐