0

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

bhavya a
  • 1
  • 1
  • 2

3 Answers3

0

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;
    });
}
Priyen Mehta
  • 1,096
  • 1
  • 5
  • 19
0

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

Omar Dieh
  • 500
  • 3
  • 8
  • this makes the file content overrided by "My cached data". I should see the data which is in the provided filename – bhavya a Jul 11 '22 at 05:19
0

This worked for me

import axios from 'axios';
  
  <a
    href={downloadFileUrl}
    onClick={() => axios.get(downloadFileUrl)}
  >
    Download File
  </a>

bhavya a
  • 1
  • 1
  • 2