Looking for a way to zip a selected folder upon upload using JavaScript on the client side. When users select a folder through the upload button, I want to maintain the same folder structure and zip it before uploading it to the backend server.
After doing some research: I came across a method that creates a Zip archive, but it compresses all files within the folder without preserving the folder structure.
What I need is to zip the folder while keeping its original structure intact.
Below are the code snippet and library references I used:
JSFiddle link: JSFidler
JSZip official website:
JSZip npm package: https://www.npmjs.com/package/jszip
The JavaScript function looks like this:
<-- HTML -->
<input id="uploadID" type="file" accept=".zip" webkitdirectory>
//JavaScript
uploadfolder(e){
var zip = new JSZip();
var fileslist = event.target.files;
var files = zip.folder();
for(let i=0; i<fileslist.length; i++){
console.log(fileslist[i].name);
files.file(fileslist[i].name, fileslist[i].raw, {base64: true});
}
zip.generateAsync({type:"blob"}).then(function(content) {
saveAs(content, "example.zip");
});
},