-
-
Save noszone/46d3a10f659dc9633d530e8261486d49 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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment