通过VueJS 3中的Axios从Laravel API下载pdf

eaf3rand  于 2023-01-21  发布在  iOS
关注(0)|答案(2)|浏览(206)

你好,我有一个前端与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. x1c 0d1x
有人知道这个问题吗?

2hh7jdfx

2hh7jdfx1#

在拉腊维尔

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

i7uq4tfw2#

答桉
responseType是标头的同级,而不是子级

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

谢谢菲尔的帮助。

相关问题