在下面的 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;
如需更多引用,您可以通过 This link
关于reactjs - 如何在react Js中从服务器位置下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58830976/