使用React和TypeScript下载文件
我正在尝试使用React构建一个单页应用程序。我想出了这种骇人听闻的方式来下载本地文件(位于public
目录中)。我有两个问题:
- 我可以更干净地写吗?
- 有什么更好或更优雅的下载本地文件的方法吗?
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:
- Can I write this more cleanly?
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 element2
. I think, better you should not place all data tohref
attribute ofa
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