7

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...

Osama Mohammed
  • 2,433
  • 13
  • 29
  • 61

1 Answers1

16

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

AjayK
  • 433
  • 5
  • 18
  • Thank you, it is seem good, but how can i use link.setAttribute('download', 'file.pdf'); how can i pass my file from API instead of (file.pdf)? – Osama Mohammed Oct 20 '18 at 16:04
  • Please follow that GIST. Api result blob should be used to create a Blob. I just gave an example of file.pdf in download attribute, you can use any file name you want as per your file type. – AjayK Oct 21 '18 at 15:14
  • @OsamaMohammed you can change the file name and the extension type as per your need. For example, if the API is returning you a file that has an extension of '.xlsx', you have to change the extension and file name accordingly. For example: link.setAttribute('download', 'my_excel_file.xlsx'); – Kazi Mar 05 '23 at 19:05
  • Is there any way to download a file without loading it into the browser?@AjayK – Jug Patel Apr 13 '23 at 11:42