Search code examples
node.jsexpresszipunzipadm-zip

Unzip file is not working


Im using the following code from

https://github.com/cthackers/adm-zip/wiki/ADM-ZIP-Introduction

Whant I need is to get a zip file from request(Im using express and I've request and response) and I need to extract(unzip) it to some path(in the example for my local drive) ,where should I put the req and what Im missing here to make it work

  fn: function (req, res) {
       var admZip = require('adm-zip');

        var zip = new admZip();

        zip.addLocalFile("C://TestFolder//TestZip");

in the request body im getting the zip file(im using postman and in the body I use the binary and select a zip file)


Solution

  • Please try my snippet code :

    For some information, My App structure like this below :

    my path --> C:\xampp\htdocs\service
    
    service
        |
        -- tmp\
        |
        -- app.js
        |
        -- index.html
    

    Client Side:

    <html>
    <body>
    <h3>ZIP Upload:</h3>
    <form action="/upload_zip" method="POST" enctype="multipart/form-data">
        Select zip to upload:
        <input type="file" name="zipFile" id="zipFile">
        <input type="submit" value="Upload ZIP" name="submit">
    </form>
    </body>
    </html>
    

    Server Side:

    Don't forget using enctype="multipart/form-data" when you post it using postman or something like that...

    var express = require("express");
    var fs = require("fs");
    var AdmZip = require('adm-zip');
    var app = express();
    
    var multer = require("multer");
    var multer_dest = multer({dest: "./tmp"}).single('zipFile');
    
    app.get("/",function(req,res){
        console.log("Show index.html");
        res.sendFile(__dirname+"/"+"index.html");
    });
    
    app.post("/upload_zip",multer_dest,function(req,res){
        console.log(req.file);  
        var zip = new AdmZip(req.file.path); 
        zip.extractAllTo("./tmp");
        result = {
            file:req.file,
            message:"File has been extracted"
        };
        fs.unlink(req.file.path, function (e) {
            if (e) throw e;
            console.log('successfully deleted '+req.file.path);
        });
        res.end(JSON.stringify(result));
    });
    
    var server = app.listen(8081,function(){
        var host = server.address().address;
        var port = server.address().port;
    
        console.log("Example App Listening at http://%s:%s",host,port);
    })
    

    Output :

    enter image description here