Zip files in React
In this tutorial we will go through how to zip given files, how to download those or how to send them to the backend. JSZip library is used for the tutorial.
First let’s implement a button to upload multiple files.
<input multiple type="file" name="file"
onChange={this.onChangeFile}/>
Then let’s implement the onChangeFile method to zip the inputed files.
First we have to install the npm package.
npm install jszip
For the zip functionality you have to use following function.
zip.file(file-name, file)
Then to generate the completed zip file.
zip.generateAsync({type: "blob})
.then(content => {
// code
});
Let’s go to the code.
const onChangeFile = () => {
const zip = require('jszip')();
let files = event.target.files;
for (let file = 0; file < event.target.files.length; file++) {
// Zip file with the file name.
zip.file(files[file].name, files[file]);
}
zip.generateAsync({type: "blob"}).then(content => {
saveAs(content, "example.zip");
});
}
saveAs
is taken from the file-saver
package in npm and if you need to send that zip file to the backend then you need to pass that content as the body as follows.
zip.generateAsync({type: "blob"}).then(content => {
axios
.post(url, content)
.then( //code );
});
Bonus Chapter
What if you need to add files to a folder then you need to add following.
folderName = zip.folder(NameOfTheFolder);
folderName.file(filename, file);
Then what if you need to add a folder inside a folder.
folderOneName = zip.folder(FolderOne);
folderTwoName = zip.folder(FolderTwo);
folderTwoName.file(filename, file);
Above will create folderTwo inside the folderOne.
Hopefully this is helpful.
If you have found this helpful please hit that 👏 and share it on social media :).