Sunday, 23 April 2017

How to make a directory, and use that new directory as variable?

Ok, So I am working on an image upload system. All the functionality works. But instead of just uploading it to uploads/images, I want to create a dir, with the randomString part of the url and store the image instide that new directory.

I can create the dir with fs.mkdir('dirNameHere'). But How can i store that newly created dir as a variable to use when storing the images, since I need to store the image in that directory? Here is the script I am working on. I can also provide code from other scripts if needed.

module.exports = function(multer, app, Image){
  var fs = require('file-system');

  // multer destination and name
  var storage = multer.diskStorage({
  

    // File destination
    destination: function(req, file, cb){
        cb(null, 'uploads/images/' + imageUrl + '/' + imageName)
    },

    // Name the file
    filename: function(req, file, cb){
        cb(null, file.originalname);
    }

  });

  var mongoose = require("mongoose");
  var Image = require("./models/image");

  var upload = multer({ storage: storage });

  app.post('/', upload.any(), function(req, res, next){
      var imageUrl = req.body.imageUrl.substr(14);
      var imageName = req.files[0].originalname; //Change to correct logic 

      // For setting expire
      // Since this is only called when the image
      // is uploaded, expireDate will persist.
      var now = new Date();
      var expirationDate = new Date();
      expirationDate.setMonth(now.getMonth() + 1);

      // If user loggedin, setOwner to username
      var setOwner;
      console.log(req.isAuthenticated());
      console.log(req.user);
      if(req.user){ setOwner = req.user.username; }
      else{ setOwner = 'Anonymous'; }

      // Create a dir with the RandomString() as name
      fs.mkdir('./uploads/images/' + imageUrl);


      var uploadImage = Image({
        image: imageName,
        url: imageUrl,
        path: 'uploads/images/' + imageUrl + '/' + imageName,
        uploadDate: now,
        expireDate: expirationDate,
        owner: setOwner
      }).save(function(err){
        if(err) throw err;
        console.log('Image Uploaded: name: ' + imageName + ' url: ' + imageUrl);
        console.log("Done :)");
        res.redirect('/' + 'image/' + imageUrl);
      });
  });
}


via Josh Beyer

No comments:

Post a Comment