Created
October 5, 2021 18:25
-
-
Save codejockie/7e82cf331111eab76ab4dbfe80975a15 to your computer and use it in GitHub Desktop.
Download a file in JS
This file contains 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
function download(fileUrl, filename) { | |
const a = document.createElement("a") | |
a.href = fileUrl | |
a.setAttribute("download", filename) | |
a.click() | |
} | |
// With Axios | |
import axios from "axios" | |
async function downloadFile(url, filename) { | |
const response = await axios({ | |
url, // File URL | |
method: "GET", | |
responseType: "blob", | |
}) | |
const file = window.URL.createObjectURL(new Blob([response.data])) | |
const docUrl = document.createElement("a") | |
docUrl.href = file | |
docUrl.setAttribute("download", filename) | |
// Optional | |
document.body.appendChild(docUrl) | |
docUrl.click() | |
} |
Author
codejockie
commented
Oct 5, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment