使用React和TypeScript下载文件

发布于 2025-01-28 17:43:51 字数 452 浏览 2 评论 0原文

我正在尝试使用React构建一个单页应用程序。我想出了这种骇人听闻的方式来下载本地文件(位于public目录中)。我有两个问题:

  1. 我可以更干净地写吗?
  2. 有什么更好或更优雅的下载本地文件的方法吗?
const handleDownload = () => {
  const tempComponent = document.createElement('a')
  tempComponent.href = 'Dark.ask'
  tempComponent.download = 'Dark.ask'
  tempComponent.click()
  tempComponent.parentElement?.removeChild(tempComponent)
}

I am trying to build a single page app using React. I came up with this hacky way to download a local file (residing in the public directory). I have two questions:

  1. Can I write this more cleanly?
  2. Is there any better or more elegant way to download a local file?
const handleDownload = () => {
  const tempComponent = document.createElement('a')
  tempComponent.href = 'Dark.ask'
  tempComponent.download = 'Dark.ask'
  tempComponent.click()
  tempComponent.parentElement?.removeChild(tempComponent)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失去的东西太少 2025-02-04 17:43:51

1。不,它始终是相同的过程:创建链接元素,将编码(BASE64,URLENCODED)数据放在链接中,以编程方式单击链接,然后删除元素

2。我认为,更好的是,您不应该将所有数据放在href a元素的属性 - 所有数据都将加载到用户RAM上。

使用stream saver: https://github.com/jimmywarting/jimmywarting/streamsaver.js
它将允许您从自定义源(例如API端点)下载任何大小的文件,


也可以在[href]中放置到静态文件的链接,当用户单击链接时,浏览器将自动开始下载,更多: https://wwwww.www.w3schools.com/tags/tags/tags/att_a_a_dowloadload。 ASP


也许重复如何使用Javascript 下载大文件

1. No, it's always the same process: create link element, put encoded (base64, urlencoded) data to the link, programmatically click the link and then remove element

2. I think, better you should not place all data to href attribute of a element - it's all will be loaded to user ram.

Use stream saver: https://github.com/jimmywarting/StreamSaver.js
It will allow you to download any size of file from custom source (like API endpoint)


Or you can just put a link to the static file in [href], and when the user clicks the link, the browser will automatically start download, more: https://www.w3schools.com/tags/att_a_download.asp.


maybe duplicate of How to download large file with JavaScript

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文