Material-UI: how to download a file when clicking a button

Viewed 13020

I know how to download a file when clicking a button using html

<a href="./abcf32x.pdf" download="How-to-download-file.pdf">
    <button>Download File</button>
</a>

But using Material-UI component how can I do this

I have the following component

<div>
  <Button
    variant="contained"
    color="#ffa726"
    size="large"
    startIcon={<GetAppIcon />}
  >
    Download Sample Method File
  </Button>
</div>

enter image description here

Now I want to download a file whose url is http://localhost:8000/static/sample_method.py

I don't want to open the link in browser and then do save as, rather it should get downloaded directly.

5 Answers

You already had your answer in the question. Instead of declaring a element with an href and download attribute using JSX syntax. Create that a element and click it programmatically:

function App() {
  const onDownload = () => {
    const link = document.createElement("a");
    link.download = `download.txt`;
    link.href = "./download.txt";
    link.click();
  };

  return (
    <Button onClick={onDownload} variant="contained" color="primary">
      Download
    </Button>
  );
}

Live Demo

Edit 66811401/reactjs-material-ui-how-to-download-a-file-on-clicking-a-button

You can also use the

file-saver

package to download your file.

To install it, run:

npm i file-saver

Then you 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.

The correct Material UI way is:

import {Button, Link} from '@mui/material'

<Button
    variant="contained"
    color="#ffa726"
    size="large"
    startIcon={<GetAppIcon />}
    component={Link}
    href="./abcf32x.pdf"
    download="How-to-download-file.pdf"
>
    Download Sample Method File
</Button>

According to the docs, I thinks this will work, and in case of using nextjs, don't forget to put that file inside the public folder

<Button variant='contained' component="label">
    <a href="/files/CV.pdf" target="_blank" download>
         Download csv
    </a>
</Button>

Related