Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download file in react

i have an Restful API i created using Laravel, this API like this:

http://127.0.0.1:8000/api/file/pdf/{id}

and this is my code for download:

public function pdfDownload($id){
       $pdf = Cv::findOrfail($id);
       return Storage::download('public/pdf/'.$pdf->pdf);
    }

it is worked in postman, and also in browser, it is directly download the file, but with react.js, it is not work, this my code in react:

pdfDownload = (id) => {
        fetch(' http://127.0.0.1:8000/api/file/pdf/' + id, {
            method: 'get',
            headers: {
                Accept: 'application/octet-stream',
                'Content-Type': 'application/octet-stream'
            }
        }).then((res) => res.json());
    };

and i call this function in button like this :

<Button color="primary" onClick={() => this.pdfDownload(data.id)}>
                                            Download
                                        </Button>

the id is corrected, i am ensure from this, my question is how can i download file when click this button.. Thans...

like image 661
Osama Mohammed Avatar asked Oct 20 '18 14:10

Osama Mohammed


Video Answer


1 Answers

XHR calls can not trigger file download, the way browser handles it. You will have to mimic a file download using javascript code yourself, using something like below:

Reference

const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();

Or use File Saver package, if you don't mind an extra dependency.

FileSaver Npm

like image 79
AjayK Avatar answered Nov 15 '22 02:11

AjayK