透過 VueJS 3 中的 Axios 從 Laravel API 下載 pdf
P粉993712159
P粉993712159 2023-11-16 12:48:50

你好,我有一個 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。

有人對這個問題有任何想法嗎?

P粉993712159
P粉993712159

全部回覆(2)
P粉610028841

在 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();
 });
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!