1

I want to upload images using multer. But it is not working. What is wrong here?

This code is in my route file.

var multer  = require('multer');
var upload = multer({ dest: 'public/uploads/' });

And this is my post route.

router.post('/addNewFood', upload.single('avatar'),function (req, res, next) {
console.log(req.files);
});
2

3 Answers 3

2

Try this, it works for me. Used express and node.

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
});

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

router.post('/addNewFood', //Your authentication check,// 
  function (req, res, next) {

    upload(req, res, function(err) {
        if (err) {
            res.redirect(req.headers.referer + "/error.html");
            return;
        }

        if (!req.files) {
            res.redirect(req.headers.referer + "/error.html");
            return;
        } else {
            //Implement your own logic if needed. Like moving the file, renaming the file, etc.
            res.redirect(req.headers.referer);
        }
    });
  }
);

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

1 Comment

Great example for including authentication... Thanks.
1

Make sure you install the package

npm install --save multer

You can try the following way, In the server side, In your routes or controller file configure the multer:

var multer = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/images/uploads')   
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname)      
    }
})
var upload = multer({ storage: storage });

In the storage object, destination is stand for, where the file will be uploaded. So make sure in your project directory, /public/images/uploads path is created. Otherwise you may want to change the file path.

Also in storage object filename is stands for, what will be the uploaded file name. Here I add the current time with the original file name to make the all file name unique.

Now in your desired routing, suppose

router.post('/', upload.single('image'), (req, res) => {
    //here your other task.
});

Now your file is uploaded. Make sure the client side is using the same name, In this case 'image'.

<input type="file" name="image" id="image" class='form-control'>

This is a single file upload procedure. For multiple files

router.post('/', upload.array(), function (req, res, next) {
  //your task goes here
});

For more information, check this link.

Comments

0

    const multer = require("multer");
 
function fileFilter(req, file, cb) {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/jpg" || file.mimetype === "image/png") {
        cb(null, true)
    } else {
        cb(null, false)
    }
    cb(new Error('I don\'t have a clue!'))
}



var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        cb(null, file.fieldname + '-' + uniqueSuffix)
    }
})

var upload = multer({
    storage: storage, limits: {
        fieldSize: 1024 * 1024 * 5,
        fileFilter: fileFilter
    }
})

 router.post("/", upload.single("image_url"),(req, res) => {
  const new User=new User({
  image_url: req.file.path
 })

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.