reactjs - 如何在 React Js 中从服务器位置下载文件
问题描述
在下面的 onclick 事件中,我点击 API 以获取文件路径,然后将该文件路径传递给下载方法----
onClick={event =>
{ event.preventDefault();this.handleDownloadDoc('downloadAPI')}}>
下载方法是:-
handleDownloadDoc = (function (fileName) {
var a = window.createElement("a");
window.body.appendChild(a);
a.style = "display: none";
return function (fileName) {
var json = JSON.stringify(fileName),
blob = new Blob([json], {type: "text/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
使用上面的代码我收到错误,因为没有创建元素。请帮助解决这个问题。
解决方案
这是从服务器下载文件的示例:-
import React from 'react';
import './download.css';
class DownloadFile extends React.Component {
constructor(props) {
super(props);
}
downloadEmployeeData = () => {
fetch('http://localhost:8080/employees/download')
.then(response => {
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'employees.json';
a.click();
});
//window.location.href = response.url;
});
}
render() {
return (
<div id="container">
<h1>Download File using React App</h1>
<h3>Download Employee Data using Button</h3>
<button onClick={this.downloadEmployeeData}>Download</button>
<p/>
</div>
)
}
}
export default DownloadFile;
如需更多参考,您可以通过此链接
推荐阅读
- python - 为什么 Sublime Text 3 给我一个“python:找不到命令”错误
- scala - 通过将 Unit 作为类型传递给泛型特征的可选方法参数
- python-3.x - 从python中的tar存档中提取压缩的gz文件
- html - 使用overflow-x进行水平滚动导航栏时出现CSS异常
- javascript - 每秒改变图像的不同问题。使用相同的图像 URL,没有数据库
- c++ - 打开文件后没有输出
- python - Python 公式创建
- jestjs - 我可以在 Jest/Enzyme 的报道报告中只包含某些方面吗
- angularjs - AngularJs - 链接 rel 样式表未在 ui-view 中使用
- hadoop - 为什么 Ceph 在仍有可用存储空间时将状态变为 Err