【问题标题】:Material-UI: how to download a file when clicking a buttonMaterial-UI:单击按钮时如何下载文件
【发布时间】:2021-03-26 05:15:30
【问题描述】:

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

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

但是使用 Material-UI 组件我该怎么做

我有以下组件

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

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

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

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您已经在问题中得到了答案。而不是使用 JSX 语法用 hrefdownload 属性声明 a 元素。创建 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>
      );
    }
    

    现场演示

    【讨论】:

    • 这仅在内容描述有附件时有效
    • 你知道为什么这不起作用吗? stackoverflow.com/questions/68666135/…@NearHuscarl
    • @325 如果您使用的是 CRA,请尝试将资产(要下载的文件)放在公用文件夹中
    • 什么是 CRA? @NearHuscarl
    • import React from "react"; import Button from "@material-ui/core/Button"; export default function DownloadFile() { const onDownload = () =&gt; { const link = document.createElement("a"); link.download = `testDownload.txt`; link.href = "./files/testDownload.txt"; link.click(); }; return ( &lt;Button onClick={onDownload} size="small" color="primary"&gt; Download &lt;/Button&gt; ); } @NearHuscarl
    【解决方案2】:

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

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

    【讨论】:

    • 不幸的是它在浏览器中打开了下载链接(例如:图像)而不是保存它
    • 应该是完整的下载链接,然后下载。
    • 不应该。该链接可能是指向页面的链接。请在此处查看此示例以下载图像。 codesandbox.io/s/…
    • 我认为它与网址有关。对于您的网址有效。你能检查一下这个网址吗——https://secure.gravatar.com/avatar/dde881ee7846ed21119d52f60dea7053
    • 是的,我做了 wget secure.gravatar.com/avatar/dde881ee7846ed21119d52f60dea7053.jpg 并且输出在下一条评论中。服务器不允许下载图片,
    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2011-02-07
    • 1970-01-01
    • 2020-12-28
    • 2019-04-29
    相关资源
    最近更新 更多