Skip to content

Instantly share code, notes, and snippets.

@raymondpittman
Last active July 28, 2024 10:29
Show Gist options
  • Save raymondpittman/11cc82788422d1bddfaa62e60e5ec9aa to your computer and use it in GitHub Desktop.
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…
/*
* @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');
@mberneis
Copy link

mberneis commented Jul 4, 2024

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