Created
October 9, 2019 14:00
-
-
Save marvinjude/8b9d42d064ff147e3dd13fd8e552d73d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Modern browsers can download files that aren't from same origin this is a workaround to download a remote file | |
| * @param `url` Remote URL for the file to be downloaded | |
| */ | |
| function Download({ url, filename }) { | |
| const [fetching, setFetching] = useState(false); | |
| const [error, setError] = useState(false); | |
| const download = (url, name) => { | |
| if (!url) { | |
| throw new Error("Resource URL not provided! You need to provide one"); | |
| } | |
| setFetching(true); | |
| fetch(url) | |
| .then(response => response.blob()) | |
| .then(blob => { | |
| setFetching(false); | |
| const blobURL = URL.createObjectURL(blob); | |
| const a = document.createElement("a"); | |
| a.href = blobURL; | |
| a.style = "display: none"; | |
| if (name && name.length) a.download = name; | |
| document.body.appendChild(a); | |
| a.click(); | |
| }) | |
| .catch(() => setError(true)); | |
| }; | |
| return ( | |
| <button | |
| disabled={fetching} | |
| onClick={()=> download(url, filename)} | |
| aria-label="download gif" | |
| > | |
| DOWNLOAD | |
| </button> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment