我有一个使用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中却无法正常工作:
这里放置需要翻译的代码
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是正确的,我确认过了。我的问题是,当点击这个按钮时,如何下载文件?谢谢。