All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

JavaScript Zip Files Before Download

Last Updated : Mar 11, 2024

JavaScript Zip Files Before Download

In this article we will show you the solution of JavaScript zip files before download, we will look towards how we can use JavaScript to zip files before starting the download.

In order to reduce their entire size and make them simpler to download and share, multiple files can be compressed into a single archive using the handy technique known as zipping.

You may improve the user interface on our web page by putting this approach into practice, especially when working with many files or big amounts of data.

We will be utilizing the well-known JavaScript a package JSZip, which offers a straightforward API for client-side generation and administration of zip files.

Employing the JSZip library, we can achieve the task of downloading files after zipping it.

For adding files and creating a zip archive the following library allow us to do it so.

We will read the chosen documents from the user's PC using JavaScript's File API before merging them to the zip bundle.

Finally, we will begin downloading the zip file containing its compressed contents.

Step By Step Guide On JavaScript Zip Files Before Download :-

Demo.html

<!DOCTYPE html>
<html>
<body>
    <input type="file" id="fileIpt" multiple />
    <button id="dButton">Download Zip</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

script.js

document.addEventListener('DOMContentLoaded', function () {
    const fileIpt = document.getElementById('fileIpt');
    const dButton = document.getElementById('dButton');
    dButton.addEventListener('click', function () {
        if (fileIpt.files.length === 0) {
            alert('Please select at least one file.');
            return;
        }
        const zip = new JSZip();
        for (let i = 0; i < fileIpt.files.length; i++) {
            const file = fileIpt.files[i];
            zip.file(file.name, file);
        }
        zip.generateAsync({ type: 'blob' }).then(function (content) {
            const downloadLink = document.createElement('a');
            downloadLink.href = URL.createObjectURL(content);
            downloadLink.download = 'files.zip';
            downloadLink.click();
        });
    });
});
  1. The programme makes use of a 'DOMContentLoaded' event listener. Whenever the HTML document's information has fully loaded and been processed, this event is executed.
  2. It develops pointers to the fileIpt and dButton HTML elements within the event handler function. These components are presumed to have the id elements 'fileIpt' and 'dButton' in the HTML language.
  3. The dButton now has an event listener that watches for click events. The inside function is activated when a button is pressed.
  4. If any documents have been chosen in the fileIpt element, it is checked within the click event handler. No documents are chosen if fileIpt.files.length = 0, in which case an alert is shown and the function is ended.
  5. It starts a fresh instance of JSZip that will be utilized for creating the ZIP file.
  6. It adds every file to the ZIP utilizing the initial name used as the file's name in the ZIP after iterating over the ones that were chosen documents (if any) within the fileIpt element.
  7. Utilizing the zip.generateAsync function, it creates a ZIP archive asynchronously as a Blob.
  8. Once the ZIP file has been successfully generated, the new downloadLink a (anchor) element has been generated.Once the ZIP file is finally successfully generated, the new downloadLink a (anchor) element gets generated.
  9. It uses URL.createObjectURL(content) to make a URL based on the Blob content for the downloadLink's href parameter. The created ZIP file is able to found at this URL.
  10. It specifies the user's usual download filename by setting the downloaded filename property of the downloadLink to 'files.zip'.
  11. At last, it uses downloadLink to dynamically initiate an action event on downloadLink.The user is prompted to save the ZIP file to their personal device using the filename "files.zip" after clicking a button that starts the ZIP file's download.

Conclusion :-

In this article, we learnt how we can use JavaScript to zip files before beginning the download.

We were able to merge several files into just one zip package on the client side by utilizing the JSZip module.

When working on big or multiple documents, this approach can considerably enhance the user knowledge, resulting in quicker and more effective downloads.

Understanding how to compress files prior download can be a useful addition to your skill set, regardless of whether you are developing a file management tool, a document-sharing platform, or any other web application that includes handling files.

I hope this article on JavaScript zip files before download helps you and the steps and method mentioned above are easy to follow name and implement.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪