4

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.

maggie
  • 85
  • 1
  • 2
  • 8

3 Answers3

7

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

Shashwat Prakash
  • 434
  • 5
  • 14
0
  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!!!

tarzen chugh
  • 10,561
  • 4
  • 20
  • 30
  • with this code nothing working on click of filename link in UI – maggie Nov 13 '19 at 06:29
  • If you run open [codesandbox link](https://codesandbox.io/s/inspiring-lumiere-4xnt1) and click on download button, it will download file with name `downloadApi.txt`. – tarzen chugh Nov 13 '19 at 07:05
  • The second code I have commented if you want to open in new window. For you case you don't need to un-comment the `open in new window` code. – tarzen chugh Nov 13 '19 at 07:21
  • No I only commented to view what's it opening and when I tried it giving blob: soemvalue and when uncommenting it doing nothing. – maggie Nov 13 '19 at 07:37
  • May you have to enable downloading from page. You have to give permission to open a file because for me the same code or codesandbox is working – tarzen chugh Nov 13 '19 at 08:54
0

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.