reactjs - 如何在react Js中从服务器位置下载文件

标签 reactjs

在下面的 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/

相关文章:

javascript - useEffect 垃圾邮件请求

reactjs - Dispatch 覆盖 React Js 中的完整存储

node.js - 使用axios发送请求时如何设置代理?

javascript - ReactJS 无法通过 onClick 重新渲染组件

javascript - 列表中的三个元素并排渲染

javascript - react 绑定(bind)到类外的常量

javascript - 如何以正确的顺序显示月份?

javascript - 是否可以在同一路径添加多个项目?

reactjs - React - 获取功能组件中的组件名称

reactjs - 使用媒体查询响应 setState