我有一个使用Laravel创建的Restful 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); }
它可以在邮递员中使用,也可以在浏览器中使用,它可以直接下载文件,但是使用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代码模仿文件下载,如下所示:
参考
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