Node.js Express Compress Files and Images to ZIP Files Using adm-zip Library Full Tutorial For Beginners 2020

Node.js Express Compress Files and Images to ZIP Files Using adm-zip Library Full Tutorial For Beginners 2020

 

 

 

Get Started

 

 

In order to get started you need to install this library and executing the given command as follows

 

npm i adm-zip

 

 

 

Source Code

 

 

Now to get started you need to create a index.html file and copy paste the following code below

 

 

 

<div class="container">
          <h1 class="text-center">
              Compress Files to ZIP File
          </h1>
          <form action="/compressfiles" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="file">Upload Files:</label>
                <input class="form-control" type="file" name="file" id="" multiple required>
            </div>
            <div class="form-group">
                <button class="btn btn-block btn-danger">
                    Download ZIP File
                </button>
            </div>
        </form>

 

index.js

 

const express = require('express')

const fs = require('fs')

const admzip = require('adm-zip')

const multer = require('multer')

const app = express()

app.get('/compressfiles',(req,res) => {

res.render('compressfiles)

})

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

var compressfilesupload = multer({ storage: storage,limits:{fileSize:maxSize}});

app.post("/compressfiles", compressfilesupload.array("file", 100), (req, res) => {
  var zip = new admzip();
var outputFilePath = Date.now() + "output.zip";
  if (req.files) {
    req.files.forEach((file) => {
      console.log(file.path)
      zip.addLocalFile(file.path)
    });
    fs.writeFileSync(outputFilePath, zip.toBuffer());
    res.download(outputFilePath,(err) => {
      if(err){
        req.files.forEach((file) => {
          fs.unlinkSync(file.path)
        });
        fs.unlinkSync(outputFilePath) 
      }

      req.files.forEach((file) => {
        fs.unlinkSync(file.path)
      });

      fs.unlinkSync(outputFilePath)
    })
  }
});


app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

READ  Build a Extreme 3D Car Driving Racing Game in Browser Using Vanilla Javascript Full Project For Beginners

 

 

 

 

 

Leave a Reply