0

I am trying to upload file to specific directory in the disk. I am using multer library. And as far as i understand this code and how it looks like now when it gets a request it takes file from it and tries to save it and it happens separately from the rest of the request. Is there a way to gain acces to full requst in let's say destination function(#1). Here is my code

var storage = multer.diskStorage({
   destination: function (req, file, callback) {
      console.log(req) // #1 here i dont see other fields from request
      callback(null, './uploads')
    },
    filename: function (req, file, callback) {
       callback(null, Date.now() + '-' + file.originalname)
    }
})

var upload = multer({ storage: storage }).single('file')

router.post('/api/photos', function (req, res, next) {
   upload(req, res, function(err) {
       console.log(req) // here i see other fields from request like req.body.description
       if (err) {return next(err)}
       res.json(201)
   })
});

What i would like to actually do is to say multer. 'Hey i want you to save file in directory /uploads/restOfThePat'. Where restOfThePath is passed in the request.

I know that i can change file location later(didnt tried this, dont know if it works). However it seems kinda hacky and i cant believe it is not possible any other cleaner way. Obviously multer is not a must, if there is some other library i would like to take a look.

1
  • anyway this file is saving in to uploads folder, inside the router.post('/api/photos') you will get the rest of the request, check the field using 'req.body.form_field' after this if you want change the destination path move the file from upload folder wherever you required using fs Commented Aug 19, 2016 at 10:03

1 Answer 1

1

You can do this:

var storage = multer.diskStorage({
   destination: function (req, file, callback) {
      console.log(req);
      callback(null, req.body.what_you_want);
    },
    filename: function (req, file, callback) {
       callback(null, Date.now() + '-' + file.originalname);
    }
})

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

router.post('/api/photos', upload.single('the_name') function (req, res, next) {
   upload(req, res, function(err) {
       console.log(req) // here i see other fields from request like req.body.description
       if (err) {return next(err)}
       res.json(201)
   })
});

It works like a charm…

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.