How to Download File in React

If you want to download a file with React.js, see this article. On this page, you will see how to download files from a server using React JS framework in three ways.

Download Files in React with the file-saver Package

In order to get download files in React, you may try the file-saver package. This will work perfectly fine. To begin with, please run the following code to install the file-saver package.
npm i file-saver

And then, you should call the saveAs function from the package. See as below. Please note that The first argument is the URL to download and the 2nd one is the file name of the downloaded file.

import React from "react";
import { saveAs } from "file-saver";

export default function App() {
  const saveFile = () => {
    saveAs(
      "https://domain/pdf/1.pdf",
      "example.pdf"
    );
  };
  return (
    <div>
      <button onClick={saveFile}>download</button>
    </div>
  );
}

Download Files in React with download Attribute

The download Attribute also allows you to download a file with React. In general, the anchor element <a> supports download Attribute. That is to say, we can add the download attribute to an anchor element if we need to download a file with React.js. By doing so, the browser will directly save the file located according to the specified URL.

import React from "react";

export default function App() {
  return (
    <div>
      <a
        href="https://domain/pdf/1.pdf"
        download
      >
        Click to download
      </a>
    </div>
  );
}

Download Files in React with Link Tag

In addition to the above two methods, you can also use a Link tag to download files in React. This is also a very simple way to achieve that. Firstly, please put your file(example.txt) into the public folder and then use a Link tag as below. Simple as that! Now, you can download the file.

<Link to="/example.txt" target="_blank" download>Download Now</Link>

By the way, it is not reliable to use front-end code to trigger a download. Because browsers will stop this action for security issues, which helps to prevent users from downloading malware. Don't worry, there is a solution. You can create an endpoint that will return the response headers to trigger the download of a file. Certainly, obtaining the user's permission is first!

Hope the above three methods worked for you.



Leave a reply



Submit