How to Download File in React Js

How to download a Docx file or msWord file using reactjs?

With "../../testFile.docx" the app is attempting to serve the file from a relative path from where the app is being hosted and served from. The testFile.docx file needs to be accessible and served correctly.

  • If serving file from the public folder

    Place testFile.docx in the public directory.

    /public
    +-/files
    +-testFile.docx

    Use an absolute path to access the testFile.docx file.

    Examples:

    • Approach 1

      const onDownload1 = () => {
      saveAs("/files/testFile.docx", "testFile.docx");
      };
    • Approach 2

      const onDownload2 = () => {
      fetch("/files/testFile.docx").then((response) => {
      response.blob().then((blob) => {
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.href = url;
      a.download = "testFile.docx";
      a.click();
      });
      });
      };
  • If imported and used locally

    import file from './testFile.docx';

    • Approach 3

      const onDownload3 = () => {
      saveAs(file, "testFile.docx");
      };
    • Approach 4

      const onDownload4 = () => {
      fetch(file).then((response) => {
      response.blob().then((blob) => {
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.href = url;
      a.download = "testFile.docx";
      a.click();
      });
      });
      };

Edit how-to-download-a-docx-file-or-msword-file-using-reactjs

How do I download file from public folder in React using Express

I think you don't need the form at all, try something like this instead:

<Fragment>
<div className="row">
<a
href="http://localhost:5000/download"
target="_blank"
className="container col-3"
>
<button className='btn btn-primary btn-block mt-4'/>
</a>
</div>
</Fragment>

In the href attribute I assume you have your server listening on port 5000, you may change it to point to your server.

Also try the behavior without the target attribute, you might not need it



Related Topics



Leave a reply



Submit