Search code examples
node.jsexpressunzipformidable

express formidable handle files


i need to unzip files uploaded anyone any ideas? The code below handles the uploading part which works with ajax. The main ideas is to get a file uploader that after uploading only ZIP files will unzip the files by creating a same name as the zip file, folder and extract everything to that folder.

also i made through html to accept only zip files but it doesnt seem like a correct solution the accept=".zip, .tar.gz, .rar" since it can easily be removed this limitation and upload whatever you want. Is there any other solution for limiting the uploads to zip files only?

var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res){
  res.sendFile(path.join(__dirname, 'public/views/index.html'));
});

app.post('/uploads', function(req, res){

  var form = new formidable.IncomingForm();

  form.multiples = true;

  form.uploadDir = path.join(__dirname, '/uploads');

  form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));
  });

  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  form.on('end', function() {
    res.end('success');
  });

  form.parse(req);

});

var server = app.listen(3000, function(){
  console.log('Server listening on port 3000');
});

Solution

  • Here's a library that you can incorporate to the code if anyone run into the same issue like me

    https://www.npmjs.com/package/unzip