0

When I try to upload a file using a post method, the req.file given by multer is returned undefined. Maybe it's not getting the correct input by name? I'm really in the dark here. Thank you in advance for your help

 //Front-end form <form action="/dashboard" method="POST" id="newproduct-form" class="row" enctype='multipart/form-data'> <input type="file" name="productImage" class="form-control-file" id="exampleInputFile"> </form> //Backend const mongoose = require('mongoose'); const multer = require('multer'); const path = require('path'); //Set Storage Engine const storage = multer.diskStorage({ destination: './public/uploads/', filename: function(req, file, cb){ cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); } }); //Init upload const upload = multer({ storage: storage }).single('productImage'); router.post('/dashboard', (req, res) => { upload(req,res,(err) =>{ if(err) console.log(err); console.log(req.file); }); } 
2
  • Your code works very well for me, Windows 10, Node v10.15. I get the following log: { fieldname: 'productImage', originalname: '1429307571797.jpg', encoding: '7bit', mimetype: 'image/jpeg'.... etc... I did create the /public/uploads directory though. What browser are you using BTW? Commented Jul 23, 2019 at 14:51
  • I'm using firefox. But I have other fields that are handled thru jQuery ajax. Can that be something to worry about? EDIT: I tested removing jquery ajax and it did log correctly... Do you know what can cause this problem? Thanks in advance Commented Jul 23, 2019 at 15:08

1 Answer 1

1

I figured it out. I was using jQuery ajax. By doing $(this).ajaxSubmit({ajax content}); instead of $.ajax({ajax content}) I managed to make it work.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.