laravel 在反应中下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52906497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:07:52  来源:igfitidea点击:

download file in react

reactjslaraveldownload

提问by Osama Mohammed

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

我有一个使用 Laravel 创建的 Restful API,这个 API 是这样的:

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:

它在邮递员和浏览器中工作,它是直接下载文件,但是使用 react.js,它不起作用,这是我在 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...

id 已更正,我确信这一点,我的问题是单击此按钮时如何下载文件..比...

回答by AjayK

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:

XHR 调用不能触发文件下载,浏览器处理它的方式。您必须自己使用 javascript 代码模拟文件下载,使用如下所示:

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.

或者使用 File Saver 包,如果你不介意额外的依赖。

FileSaver Npm

文件保护程序