你好,我有一个 VUEJS 3 的前端和 Laravel 8 的后端。我会下载保存在 public/pdf/temp/file.pdf 中的 pdf
现在我从 VUEJS 拨打电话:
axios.post('/api/'+ this.url_access +'/rebuild', formData, { headers: {
                'Content-Type': 'multipart/form-data',
                'responseType': 'blob'
            }})
            .then(response=>{
                if(response.status == 200){
                    const url = window.URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', 'test.pdf');
                    document.body.appendChild(link);
                    link.click();
                }
            })
            .catch(error=>{
                console.log(error);
            })
在后端我有一个返回pdf文件的函数:
try{
   $headers = [
       'Content-Type' => 'application/pdf',
   ];
   return response()->download($file_path, $workspace['name'] . '_' .date("Ymd").'.pdf', $headers)->deleteFileAfterSend(true);
}catch(Exception $e){
   return $e->getMessage();
}
但是我下载了空白内容的pdf。
有人对这个问题有任何想法吗?
在 Laravel 中
$pdf = PDF::loadView('users.pdf', ['data' => $data]); return $pdf->output();在 Vue js 中
axios({ url: 'http://localhost:8000/api/your-route', method: 'GET', responseType: 'blob', }).then((response) => { var fileURL = window.URL.createObjectURL(new Blob([response.data], {type: 'application/pdf'})); var fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', 'file.pdf'); document.body.appendChild(fileLink); fileLink.click(); });回答
responseType 是 headers 的同级,而不是子级
axios.post('/api/'+ this.url_access +'/rebuild', formData, { headers: { 'Content-Type': 'multipart/form-data', }, 'responseType': 'blob' // responseType is a sibling of headers, not a child }) .then(response=>{ if(response.status == 200){ const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'test.pdf'); document.body.appendChild(link); link.click(); } }) .catch(error=>{ console.log(error); })感谢菲尔的帮助。