Last active
July 28, 2024 10:29
-
-
Save raymondpittman/11cc82788422d1bddfaa62e60e5ec9aa to your computer and use it in GitHub Desktop.
Native Javascript, automatically download a BLOB zip file using FETCH without the use of manual triggering clicking a DOM element. Will create a DOM element automatically and set the attribute HREF to a zip file or contents, then download file automatically on HTML file page load. Or also, will work through Node.js or another Fetch compatible Ja…
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
/* | |
* @Author Raymond Pittman | |
* @Github: https://github.com/raymondpittman | |
* @Note: Added README.md https://gist.github.com/raymondpittman/11cc82788422d1bddfaa62e60e5ec9aa | |
*/ | |
/* | |
* @params | |
* @download: http://.zip | |
* @filename: ./downloaded.zip | |
*/ | |
function download(url, filename) { | |
fetch(url, { | |
mode: 'no-cors' | |
/* | |
* ALTERNATIVE MODE { | |
mode: 'cors' | |
} | |
* | |
*/ | |
}).then((transfer) => { | |
return transfer.blob(); // RETURN DATA TRANSFERED AS BLOB | |
}).then((bytes) => { | |
let elm = document.createElement('a'); // CREATE A LINK ELEMENT IN DOM | |
elm.href = URL.createObjectURL(bytes); // SET LINK ELEMENTS CONTENTS | |
elm.setAttribute('download', filename); // SET ELEMENT CREATED 'ATTRIBUTE' TO DOWNLOAD, FILENAME PARAM AUTOMATICALLY | |
elm.click() // TRIGGER ELEMENT TO DOWNLOAD | |
}).catch((error) => { | |
console.log(error); // OUTPUT ERRORS, SUCH AS CORS WHEN TESTING NON LOCALLY | |
}) | |
} | |
/* | |
* @CALL | |
* EXAMPLE LOCAL FUNCTION CALL | |
*/ | |
download('http://.zip', 'test.zip'); |
Thank you - you saved my day - was trying for a few hours to get this done.
I needed this in a page showing a spinner and redirect back to the issuing page after the download.
Your code made that possible - Just had to a final then
.then(() => {
history.back();
})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately the updated solution does not work when the file is served without
Access-Control-Allow-Origin:*
header.We can use
open()
,FileSystemObserver
, and File System Access API with JSZip to download, extract and write the extracted files and folders to the local filesystem, with the caveat that file permissions are not preserved.