Kwall
Kwall

Reputation: 549

How can create button component for direct download the file in reactjs?

I have a api which has a file link. Here I need to create a button So when the user is clicked on then the file will directly download on his system.All I want in reactjs.

I have gone through this post. But the problem is How can we create and apply on button component?

I tried with these code

response.blob().then(blob => {
    let url = window.URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.href = url;
    a.download = 'employees.json';
    a.click();
});
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/>
                <h3>Download Employee Data using Link</h3>
                <a href="#" onClick={this.downloadEmployeeData}>Download</a>
            </div>
        )
    }

}

export default DownloadFile;

And nothing is come on console and no event is happning.

Upvotes: 0

Views: 535

Answers (1)

amdev
amdev

Reputation: 7442

you can easily create a button that holds a tag with the attribute of download in it, like below:


return (
  <div>
   ... some other elements 

   {setCurrContest.download_brief && (
     <button>
       <a href={setCurrContest.download_brief} download>
         SOME TEXT TO DOWNLOAD
       </a>
     </button>
   )}

   .. some more jsx
  </div>
)


It will automatically bring the download popup (regardless of the users platform) and you are not going to need all that click handler stuff!

Upvotes: 3

Related Questions