1

multer.js

var path = require("path"),
multer = require("multer");

const storage = multer.diskStorage({
    destination: function(req, file, next){
        next(null, '../public/imgs/');
        return;
    },
    filename: function(req, file, cb){
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

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

module.exports = upload;

router.js

//handle createPartner route
router.post("/partner/new", upload.single('image'), function(req, res){

  console.log(req.file);
  console.log(req.body);

  req.body.Partner["image"] ="/static/imgs/"+req.file.filename;

  req.body.Partner.body = req.sanitize(req.body.Partner.body);

  Partner.create(req.body.Partner, function(err, createdPartner){
      if(err){
          console.log(err);
          res.redirect("/admin/partner/new");
      }else{
          res.redirect("/partners");
      }
  });
});

I get the following console.log

{ fieldname: 'image',
  originalname: 'fb.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: '../public/imgs/',
  filename: 'image-1521727739861.png',
  path: '../public/imgs/image-1521727739861.png',
  size: 21532 }
{ Partner: { name: 'test', bio: 'test', image: '', website: 'test' } }

so multer does get the file but it doesn't upload it to the destination! The permissions for /public and /public/imgs are 777. Everywhere I searched uses the other method for multer but that way I'll have to specify (single/multiple/any) in advance which isn't right.

2
  • I have had a similar issue in the past and it was to do with my destination path not being correct. To test it out, you can try putting in the full path to your images from folder from your root directory. e.g. if you're on mac /Users/<computername>/project/public/imgs/ Commented Mar 22, 2018 at 14:23
  • Thanks this worked! but it doesn't seem right at all. I mean I'll have to keep updating the path when deploying, why can't it be relative? Commented Mar 22, 2018 at 14:31

1 Answer 1

1

You need to include the absolute path as I mentioned in comments.

You can easily do this by utilising path.join like follows:

var path = require('path');
var dir = path.join(__dirname, '../public/imgs')

That will concatenate __dirname which is the absolute path of the current file with your images file.

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

1 Comment

No problem @KaisSalha. Please mark answer as correct if it helped

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.