Home > Software engineering >  Download pdf via Axios in VueJS 3 from Laravel API
Download pdf via Axios in VueJS 3 from Laravel API

Time:08-29

hello I have a frontend with VUEJS 3 and backend Laravel 8. I would download a pdf saved in public/pdf/temp/file.pdf

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

and in the backend I have a function that return 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 blank content pdf. enter image description here

Anyone have any idea for this problem?

CodePudding user response:

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

Thank you for Phil helping.

  • Related