download file in react

后端 未结 1 1574
谎友^
谎友^ 2021-01-24 17:58

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:

相关标签:
1条回答
  • 2021-01-24 18:31

    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

    0 讨论(0)
提交回复
热议问题