简体   繁体   中英

NodeJS file upload with multer

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.

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…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM