0

I'm trying to make a simple app to allow an upload of a .zip file, unzip it in memory, and save to MongoDB Atlas.

I have tried out a few functions and routes, but it's not behaving as I would like.

I can upload the file to the database while it's zipped. I can also upload the zipped file to disk storage and unzip it and save it to another directory, but I cant upload the unzipped file to the DB without explicitly specifying the file name in the path, which of course is useless as it isn't dynamic.

  • This upload it to disk storage and then unzips it to another dir:
//SET STORAGE
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/unzip')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})
var upload = multer({ storage }).single('file');

const postfile = (req, res, next) => {
  const { title, description } = req.body
  const viles = req.file
  console.log("Request ---", req.file);
  console.log("Body ---", req.body);
   if (!file) {
    const error = new Error('Please upload a file')
    error.httpStatusCode = 400
    return next(error)
  }
  const dir = req.file.path;
  const newDir = './uploads/unzipped';
  fs.createReadStream(dir)
    .pipe(unzipper.Extract({ path: newDir }));
     res.send(file)
     return next()
};
  • This is different module where I am trying to unzip the file in memory and send to db, but it isn't working:
const GridFsStorage = require('multer-gridfs-storage');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var AdmZip = require('adm-zip');

const mongoUri = 'mongodb+srv://USER:PASSWORD@cluster/test?retryWrites=true&w=majority'


//init gfs
let gfs; 

var conn = mongoose.createConnection(mongoUri);
conn.once('open', () => {
  gfs = Grid(conn.db);
  gfs.collection('uploads')

  // all set!
})

//create grid storage
const storage = new GridFsStorage({
  url: mongoUri,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      var file = new AdmZip(req.file);

        const filename = file.originalname + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'uploads'
        };
        resolve(fileInfo);
    });
  }
});
const upload = multer({ storage }).single('file');

const postfile = (req, res) => {
  res.json({file: file})
}
pppery
  • 3,731
  • 22
  • 33
  • 46
Nancy Collins
  • 197
  • 4
  • 13
  • 1
    before anything else, you should update the password to your mongo database! It's generally best to limit access to expected IP addresses too. – klhr Sep 10 '19 at 00:55
  • I actually just grabbed the suggested string from MongoDB before I posted it here as I haven't encrypted the password yet. I'm still at very early stages of making my App so I'm focusing on basic functionality first, thank you though. – Nancy Collins Sep 10 '19 at 13:59

0 Answers0