我有一个使用 Laravel 创建的 Restful API,这个 API 是这样的:
http://127.0.0.1:8000/api/file/pdf/{id}
这是我的下载代码:
public function pdfDownload($id){
$pdf = Cv::findOrfail($id);
return Storage::download('public/pdf/'.$pdf->pdf);
}
它在 postman 中工作,也在浏览器中直接下载文件,
但是对于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());
};
我在按钮中调用这个函数,如下所示:
<Button color="primary" onClick={() => this.pdfDownload(data.id)}>
Download
</Button>
id 已更正,我确信这一点,我的问题是单击此按钮时如何下载文件..比...
最佳答案
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();
或者使用 File Saver 包,如果你不介意额外的依赖。
FileSaver Npm
关于reactjs - 在 react 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52906497/