maggie
maggie

Reputation: 95

How to download the file from server location in react Js

On below onclick event I am hitting the API to get the filepath and then passing that filepath to download method----

onClick={event => 
                    { event.preventDefault();this.handleDownloadDoc('downloadAPI')}}> 

Download method is :-

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);
    };
}());

with above code I am getting error as does not create Element. Please help to fix this up.

Upvotes: 5

Views: 35435

Answers (3)

Sanjeeb Kumar Sahoo
Sanjeeb Kumar Sahoo

Reputation: 21

const url = window.URL.createObjectURL(new Blob([_response?.data]),);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download',Report.csv, // File name with type
                );
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);

Try this one.

Upvotes: 0

tarzen chugh
tarzen chugh

Reputation: 11247

  1. You don't need IIFE to execute the code.

  2. You don't need to create arrow function inside the render method.

Working code below and codesandbox link:-

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  handleDownloadDoc = fileName => e => {
    // Downloads the file
    const link = document.createElement("a");
    link.download = `${fileName}.txt`;
    const blob = new Blob(["Hello, world!"], { type: "text/plain" });
    link.href = URL.createObjectURL(blob);
    link.click();
    URL.revokeObjectURL(link.href);

    // Opens in new window
    // const blob = new Blob(["Hello, world!"], { type: "text/plain" });
    // const fileURL = URL.createObjectURL(blob);
    // window.open(fileURL);
  };
  render() {
    return (
      <div className="App">
        <button onClick={this.handleDownloadDoc("downloadApi")}>
          Download
        </button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope that helps!!!

Upvotes: 0

Shashwat Prakash
Shashwat Prakash

Reputation: 484

This is the example for download a file from server:-

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;

For more reference you can go through This link

Upvotes: 9

Related Questions