Skip to content

Instantly share code, notes, and snippets.

@raed667
Last active September 14, 2020 12:44
Show Gist options
  • Save raed667/d82ba856178da0bb24af2d2b7b83ee9f to your computer and use it in GitHub Desktop.
Save raed667/d82ba856178da0bb24af2d2b7b83ee9f to your computer and use it in GitHub Desktop.
Download a file using axios (works with Chrome, FireFox, Safari, Edge, IE)
import axios from "axios";
export const download = async (uuid) => {
const { data } = await axios({
url: `/api/download/${uuid}`,
method: "GET",
responseType: "blob",
});
const blob = new Blob([data], {
type: "application/pdf",
});
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(blob, "file.pdf");
} else {
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "file.pdf");
if (typeof link.download === "undefined") {
link.setAttribute("target", "_blank");
}
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}, 100);
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment