Categories
React Answers

How to Download File in React.js?

Spread the love

To download a file with React.js, we can add the download attribute to an anchor element.

For instance, we can write:

import React from "react";

export default function App() {
  return (
    <div>
      <a
        href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
        download
      >
        Click to download
      </a>
    </div>
  );
}

We just add the download prop to do the download.

If we don’t want to use an anchor element, we can also use the file-saver package to download our file.

To install it, we run:

npm i file-saver

Then we can call the saveAs function from the package by writing:

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

export default function App() {
  const saveFile = () => {
    saveAs(
      "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
      "example.pdf"
    );
  };
  return (
    <div>
      <button onClick={saveFile}>download</button>
    </div>
  );
}

The first argument is the URL to download and the 2nd argument is the file name of the downloaded file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Download File in React.js?”

The file-saver is good library but i have an issue with the filename. If the file has ( or other special character, the file-saver will turn the file filename.jpg with underscore in between the filename.

Leave a Reply

Your email address will not be published. Required fields are marked *