Search code examples
javascriptzipjszip

Upload Image,convert it to zip( client side ) and then upload to server


Upload image file,and convert it to zip on client side and then upload ( converted zip ) file to server. There is a js jsZip can convert image file to zip on client side,but the question is that how can i upload this converted zip file to server directly.


Solution

  • Use jsZip

    Upload file using HTML

    <form action="/your-action"> <input type="file" id="mypicid" name="pic"> <button onclick =" myFunction() "> Upload <button> </form>

    On upload click convert files to zip

      function myFunction(){
    
    /* Make a zip file here */
    
     var fi = document.getElementById("mypicid");
     var fileInput = fi;
     var files = [];
    
     // get all selected file
    
     $.each(fileInput.files, function(i, file) {
        files.push(file);
     });
    
     //create a zip object
    
      var zip = new JSZip();
    
     //add all files to zip 
    
     function addFileToZip(n) {
         if(n >= files.length) {
    
    //here generate file to zip on client side
            zip.generateAsync({type:"blob", compression:"default"}).then(function(content){
    
            //generated zip content to file type
                var files = new File([content], "name.zip");
    
                 var formData = new FormData();
                 formData.append('fileZip', files);
    
            //send generated file to server
                 $.ajax({
                    data: formData,
                    url : '/your_path',
                    type : 'POST',
                    processData: false,
                    contentType: false,
                    success : function(response) {
                         alert("success");
                    }
                });
    
            return;
        }
        var file = files[n];                    
        var arrayBuffer;
        var fileReader = new FileReader();
        fileReader.onload = function() {
            arrayBuffer = this.result;
            zip.file(file.name, arrayBuffer);
            addFileToZip(n + 1);
        };
        fileReader.readAsArrayBuffer(file);
    }
    addFileToZip(0);
    }