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

标签 laravel vue.js

我用 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/

相关文章:

laravel - 如何在 laravel 模块中进行迁移?

php - Laravel:在 Controller 中同时使用两个请求

php - 如何在 laravel 5.8 中用新名称覆盖 $request 数组中的文件名

jquery - 使用jquery附加vue js组件

node.js - Nuxt js错误找不到页面目录

javascript - 动态创建的输入。无法使用 $refs 那么如何获取例如重点?

vue.js - 如何在组件之间传递状态?

javascript - 在 Laravel 5.4 中使用 Ajax 刷新选择下拉数据

php - 可以将Docker镜像设为 “built” (“compiled”)而不要求Docker吗?

javascript - 在方法对象的函数内发出自定义事件