Skip to content

Instantly share code, notes, and snippets.

@raymondpittman
Last active February 5, 2024 17:56
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');
@akashrokade
Copy link

giving 0 byte zip file

@Iamouad
Copy link

Iamouad commented May 29, 2021

Worked perfectly, thanks man.

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment