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');
@raymondpittman
Copy link
Author

Worked perfectly, thanks man.

Mg pleasure. Glad to help.

@raymondpittman
Copy link
Author

raymondpittman commented Jun 1, 2021

giving 0 byte zip file

Added a README.md to help you out.

// CODE

/*
 * @Author Raymond Pittman
 * @Github: https://github.com/raymondpittman
 * @Note: Added README.md
 */

/*
 * @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');

Environment Testing

Tested Working - Tuesday, June 1st, 2021

Steps Recreating - Testing

  • WebStorm IDE index.html <script>//content//</script>or a
    simple HTTP server. Not HTTPS, will work over HTTPS when CORS is changed in script settings.

  • Non-CORS Mode is set, meaning the http://localhost/example.zip file
    is downloaded locally for testing
    over a non HTTPS protocol, using instead over the HTTP protocol.
    Or, simply testing downloading a ./example.zip local zip file
    from the folder location in testing folder environment.

  • The fetch mode object value is set to no-cors, simple HTTP testing is
    required. This will avoid any cross domain errors. Errors such as 0 byte .zip
    file's being downloaded or browser console errors such as:

    ERROR: No 'Access-Control-Allow-Origin'

    This error comes from downloading a .zip file from a non-HTTP URL
    over your testing server. Such as requesting the function by calling:

    download(`https://domain.com/example.zip`, `./output.zip`);

    Instead of just testing locally before production using HTTP or local disk, notice
    the fact the download URL begins with HTTPS.

    { mode: no-cors }

    Test instead by calling the function to download locally over a HTTP
    protocol and or local file location example as such
    over the disk folder location as such:

    download(`./example.zip`, `./output.zip`)

So simply start a simple web server, download a sample .zip file, or create one. Move
the zip file to the folder path location of the index.html file
that is being served to make things simple. Then name the zip file as example.zip.
Then simply all you do is within the script tags of a HTML file.

function download(url, filename) {
    fetch(url, {
        mode: 'no-cors' // NO 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
    })
}

download('./example.zip', './output.zip');      // LOCAL DISK - Location - Download
  • Creates a DOM element automatically and triggers the download once the page loads,
    no need for creating download links or HTML elements. As
    this script will do this itself. And when in production you will change
    the no-cors object settings in the script.

Read Up:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

@guest271314
Copy link

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.

@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