Home > Back-end >  Is it possible to download file from external url using anchor tag in react?
Is it possible to download file from external url using anchor tag in react?

Time:07-10

usecase: when use clicks on "Download File", an external file associated with it should get downloaded to user's matchine.

I tried : 1.

<a href={downloadfileUrl} download={downloadfileUrl}>
        <div className="filename" data-testid="download-link-filename">
          Download file
        </div>
      </a>
<Link
        // href={downloadfileUrl}
        target="_blank"
        to={{ pathname: {downloadfileUrl} }}
        download
      >
        Download Template
      </Link>

Tried above with many combinations. It's not working, I can see "Download file" hyperlink on UI but it does not download the file when I click on it. Can someone suggest any solutions

CodePudding user response:

Try this function and replace your url in fetch it might works!

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

CodePudding user response:

one solution would be the react-download-link package :

  1. install with npm install --save react-download-link
  2. Include with import DownloadLink from "react-download-link";
  3. Use :
<DownloadLink
    label="Save"
    filename="myfile.txt"
    exportFile={() => "My cached data"}
/>

package official link

  • Related