Skip to content

Instantly share code, notes, and snippets.

@marvinjude
Created October 9, 2019 14:00
Show Gist options
  • Select an option

  • Save marvinjude/8b9d42d064ff147e3dd13fd8e552d73d to your computer and use it in GitHub Desktop.

Select an option

Save marvinjude/8b9d42d064ff147e3dd13fd8e552d73d to your computer and use it in GitHub Desktop.
/**
* 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