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

Viewed 632

I have been trying to figure out how can I create a download functionality when a user clicks on a button.

I tried to use the File save library but the result is not as expected, also I tried a turnaround and used a different approach but again the same.

When I download the file using the 2nd approach that is by using fetch API the file am getting is a corrupted file. Please see the code below with the codeSandbox link as well.

Approach 1

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

Approach 2

const onDownload2 = () => {
    fetch("../../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();
      });
    });
  };

Full source code link

Click to open in codeSandbox.

Thanks for the help and time.

1 Answers

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

Related