My problem is that I can't get the req.body and req.file object when I post to /new, but everything is fine and the file is being uploaded in my folder. I just can't get access to the req.body and req.file objects. It returns [object Object] when I log req.body in the console and for req.file it logs undefined.
I've done some research and I found that you can't encode multipart/form-data with body-parser, but I need to have it because I can't send files without it.
var router = require('express').Router(),
multer = require('multer'),
path = require('path'),
passport = require('passport'),
middleware = require('../middleware'),
User = require('../models/User'),
Ad = require('../models/Ad');
// Storage setup
var storage = multer.diskStorage({
destination: './public/uploads/',
filename: function(req, file, done) {
done(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Upload setup
var upload = multer({
storage: storage,
limits: {
fileSize: 3000000
}
}).single('banner');
// Check file type
function checkFileType(file, callback) {
// Allowed extensions
var fileTypes = /jpeg|jpg|png|gif/;
// Check extention
var extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
// Check mime type
var mimeType = fileTypes.test(file.mimetype);
if (mimeType && extname) {
return callback(null, true);
}
callback(null, false);
}
router.get('/new', middleware.isLoggedIn, function(req, res) {
res.render('new');
});
router.post('/new', middleware.isLoggedIn, function(req, res) {
var adObj = {
owner: req.user,
url: req.user.url,
paymentType: req.body.paymentType,
transactionId: '',
banner: ''
};
if (adObj.paymentType === 'paid') {
adObj.transactionId = req.body.transactionId;
}
upload(req, res, function(err) {
if (err) {
req.flash('error', err.message);
return res.redirect('/new');
}
adObj.banner = '/uploads/' + req.file.filename;
});
var ad = new Ad(adObj);
ad.save();
req.flash('success', 'Successfully added new ad.');
res.redirect('/');
});
<form class="main-form" action="/new" method="POST" enctype="multipart/form-data">
<input type="url" name="url" placeholder="Website URL" required>
<select class="select-ad-type" name="paymentType">
<option value="free" selected>Free Ad</option>
<option value="paid">Sponsored Ad - $10</option>
</select>
<div class="transaction-section">
<p>Send $10 to [email protected] and type your transaction id below. Your ad will be displayed in the "SPONSORED ADS" section in less than 24 hours.</p>
<input type="text" name="transactionId" placeholder="Transaction Id">
</div>
<input type="file" name="banner" required>
<button><i class="fa fa-plus" aria-hidden="true"></i> SUBMIT</button>
</form>
You are getting the errors because you are trying to access the values before actual parsing by multer
happens. You have rightly pointed out that body-parser
doesn't work for multipart-data
, but in multipart-data
form-type, multer
can parse both file
and other fields in the form
, that's why we can access both req.file
and req.body
.
Make sure you access it in upload(req, res, function(err) { // req.body and req.file })
Also, there is an issue related to asynchronous code.
Solution:
router.post('/new', middleware.isLoggedIn, function(req, res) {
upload(req, res, function(err) {
if (err) {
req.flash('error', err.message);
return res.redirect('/new');
}
var adObj = {
owner: req.user,
url: req.user.url,
paymentType: req.body.paymentType,
transactionId: '',
banner: ''
};
if (adObj.paymentType === 'paid') {
adObj.transactionId = req.body.transactionId;
}
adObj.banner = '/uploads/' + req.file.filename;
var ad = new Ad(adObj);
ad.save();
req.flash('success', 'Successfully added new ad.');
return res.redirect('/');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With