Material-UI:如何在单击按钮时下载文件

San*_*idi 9 reactjs material-ui

我知道如何在使用 html 单击按钮时下载文件

<a href="./abcf32x.pdf" download="How-to-download-file.pdf">
    <button>Download File</button>
</a>
Run Code Online (Sandbox Code Playgroud)

但是使用 Material-UI 组件我该如何做到这一点

我有以下组件

<div>
  <Button
    variant="contained"
    color="#ffa726"
    size="large"
    startIcon={<GetAppIcon />}
  >
    Download Sample Method File
  </Button>
</div>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我想下载一个文件,其url是http://localhost:8000/static/sample_method.py

我不想在浏览器中打开链接然后另存为,而是应该直接下载。

Nea*_*arl 7

你在问题中已经有了答案。而不是使用 JSX 语法声明a带有hrefanddownload属性的元素。创建该a元素并以编程方式单击它:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

现场演示

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


小智 0

您可以使用onClick按钮的事件处理程序来获取事件回调,并使用以下链接中的以下代码来下载文件。

https://codesource.io/how-to-download-file-in-javascript/