Compressing single file or multiple files to zip format on client side

Stewart Tan
Nov 7, 2019 · 3 min read
Photo by JJ Ying on Unsplash

Sending single file or multiple files by user to network which may consume a lot of network traffic, which in turn causing the network cost increase. One of the method to reduce the network data traffic is reduce the amount of data send to server by compressing the upload file(s). In this method, we are introducing Javascript library JSZip which is capable to compress files into .zip format.

Let’s create project directory, init npm package and install JSZip as dependancy. We are also going to use webpack as bundling tool. More details for the webpack can find in the webpack official website. In this tutorial, we will not dive into webpack in detail as the purpose of this article is to emphasize on compressing the files.

npm init -y
npm i jszip
npm i webpack webpack-cli webpack-dev-server --save-dev

In the project directory, we create our main page index.html in the distribution(dist) folder and our javascript working file in source(src) directory as below:

Next, we create the webpack configuration file in root project directory. The webpack will based on the configuration file and look for index.js, bundled and output as main.js to the dist folder.


We also need to add script to our package.json as follow in order to start our dev server using npm script:

For our main html page (index.html), we create one input field for users to upload files with multiple file selection enabled. We also include our bundled javascript in the main html page.


Next, in index.js javascript files, we get the input element using getElementById and attached change event listener to listen to file change when user selected the files. Loop through each of the file from FileList object to get the filename and pass together with file to zip object. Last, we generate the complete zip file by calling generateAsync method. In below example, we set blob as output type which we will use it to test the result by triggering a download link by click.


Now, we can start up the webpack dev server using npm start. Once started, navigate to http://localhost:9000 and try select multiples file to see the result.

npm start

In this example, this can only support compressing file size up to medium size (~ 50Mb) as it will slow down the webpage when the upload files are large due to javascript is single threaded. One of the method to improve this is implement the zip compression in web worker which we will talk in next article.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade