'Downloading a file using React and Typescript
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)
}
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |