Download pdf from Laravel API via Axios in VueJS 3
P粉993712159
P粉993712159 2023-11-16 12:48:50
0
2
825

Hello, I have a VUEJS 3 front-end and Laravel 8 back-end. I will download the pdf saved in public/pdf/temp/file.pdf

Now I make a call from 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); })

In the backend I have a function that returns a pdf file:

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

But I downloaded the pdf with blank content.

Does anyone have any thoughts on this issue?

P粉993712159
P粉993712159

reply all (2)
P粉610028841

In Laravel

$pdf = PDF::loadView('users.pdf', ['data' => $data]); return $pdf->output();

In 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(); });
    P粉722521204

    answer

    responseType is a sibling of headers, not a child

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

    Thanks Phil for the help.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!