I'm trying to upload images with Multer in Node.js. When I console.log(req.files) it gives undefined.What is wrong here?
<form class="form-horizontal" enctype='multipart/form-data' action="/admin/addNewFood" method="post">
<div class="form-group">
<label for="image" class="col-sm-2 control-label">Choose Image</label>
<div class="col-sm-3">
<span class="btn btn-default btn-file btn-xs">
Browse <input type="file" name="fileUpload">
</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="hidden" name="_csrf" value="{{ csrfToken }}">
<button type="submit" class="btn btn-default">Add</button>
</div>
</div>
</form>
This is my route file
var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var passport = require('passport');
var Cart = require('../Models/cart');
var multer = require('multer');
var upload = multer({ dest: '../public/uploads/' });
var bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.use(upload.single('fileUpload'));
var csrfProtection = csrf();
router.use(csrfProtection);
router.post('/addNewFood', function (req, res, next) {
console.log('filesssssssss',req.files);
}
});
I can't figure out what is wrong here.Please help
I am upload a file using this , hope this works for you as well.
var express = require('express');
var mongoose = require('mongoose');
var multer = require('multer');
var fs = require('fs');
var Grid = require('gridfs-stream');
var router = express.Router();
var upload = multer({dest: 'uploads/'});
router.post('/upload', upload.any(), function (req, res) {
var conn = mongoose.connection;
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var path = req.files[0].path
var path_name = req.files[0].originalname
var gfs = Grid(conn.db);
var writestream = gfs.createWriteStream({
filename: path_name
});
fs.createReadStream(path).pipe(writestream);
writestream.on('close', function (file) {
fs.unlink(req.files[0].path, function () {
res.json({id: file._id, message: "success"});
});
});
})
Related
editUser.js which is loading the data correctly, however when clicking on update I am getting (404 not found error), not able to understand why update route is not getting invoked. It is working for /, createUser, editUser/:id (for loading user data).
editUser.js
<div class="container">
All Users
<form class="col g-3 mt-3"" method="post" action="/update/<%= user.id %>">
<div class="col-md-6">
<label for="inputFirstName" class="form-label">First Name:</label>
<input type="text" class="form-control" value="<%= user.first_name %>" name="first_name" id="first_name">
</div>
<div class="col-md-6">
<label for="inputLastName" class="form-label">Last Name</label>
<input type="text" class="form-control" value=<%= user.last_name%> name="last_name" id="last_name">
</div>
<div class="col-md-6">
<label for="inputEmail" class="form-label">Email</label>
<input type="email" class="form-control" value=<%= user.email%> name="email" id="email">
</div>
<div class="col-md-6 mt-3">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
routes/index.js
var express = require('express');
var router = express.Router();
var {allUsers, createUser, saveUser, editUser, updateUser} = require('../controllers/userController')
/* GET users listing. */
//Commenting default function
router.get('/', allUsers)
router.get('/createUser', createUser)
router.post('/createUser', saveUser)
router.get('/editUser/:id', editUser)
router.post('/updateUser/:id', updateUser)
module.exports = router;
controllers/userController.js
const User = require('../models/userModel')
const updateUser = async (req, res) => {
console.log('Updating User')
const userId = req.params.id
const userData = req.body
const selector = {where: {id:userId}}
await User.update(userData, selector).catch(error => console.log(error))
res.redirect('/')
}
module.exports = { allUsers,createUser,saveUser,editUser,updateUser }
app.js
//Imports
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressLayouts = require('express-ejs-layouts')
const routes = require('./routes');
//DOTENV for storing sensitive data
require('dotenv').config({path:'./bin/.env'})
var app = express();
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); //Key, Value
app.set('layout','layouts/layout')
//Middleware between requet and response
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressLayouts)
//Use Router
app.use('/',routes)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
//error handler first parameter is "err"
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Form action should be action="/updateUser/<%= user.id %>
In my Node app i have a simple form like this:
<form action="/createProject" enctype="multipart/form-data" method="post">
<div class="project-field">
<p class="subtitleFont project-field-name">NOME</p>
<input type="text" name="name" required>
</div>
<div class="project-field">
<p class="subtitleFont project-field-name">IMMAGINI</p>
<input type="file" multiple name="images" required>
</div>
<div class="project-field">
<button type="submit">Crea progetto</button>
</div>
</form>
This is the app.js configuration:
require('dotenv').config();
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const routes = require('./server/routes/index.js');
const app = express();
const port = process.env.PORT;
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.use(expressLayouts);
app.use(routes);
app.set('layout', './layouts/main');
app.set('view engine', 'ejs');
app.listen(port, () => {console.log('Listening to port '+port+'!')});
The multer configuration is this:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, 'public/uploads/');
},
filename: function(req, file, cb){
cb(null, new Date().toISOString() + file.originalname);
}
})
const upload = multer({storage: storage});
When i trigger the action and console.log serverside req.body and req.files they seem to be empty.
Is there any way to solve this problem?
My code is extremely simple and almost follow the tutorial on Multer git, but my req.file is still undefined:
Here's my html to upload the image:
<form action="/product/upload_image" enctype="multipart/form-data" method="POST">
<input id="product_image" type="file" name="product_image" accept=".png,.jpg,.jpeg"/>
<input type="submit" value="Upload image"/>
</form>
My routes:
var multer = require("multer")
var upload = multer({ dest: "uploads/" })
router.post("/product/upload_image", upload.single("product_image"), function(req, res) {
console.log(req.file)
}
And it returns undefined
Server.js
const express = require('express');
const app = express()
const path = require('path')
const indexRouter = require('./index.js')
app.use('/', indexRouter)
const PORT = 5000;
app.listen(PORT, () => console.log('it started on 5000'))
index.js
const express = require('express');
const router = express.Router()
var multer = require("multer")
var upload = multer({ dest: "uploads/" })
router.get('/', (req, res) =>
res.sendFile('upload.html', {root: __dirname })
)
router.post("/product/upload_image", upload.single("product_image"), (req, res)=>
console.log(req.file)
)
module.exports = router
upload.html
<form action="/product/upload_image" enctype="multipart/form-data" method="POST">
<input id="product_image" type="file" name="product_image" accept=".png,.jpg,.jpeg"/>
<input type="submit" value="Upload image"/>
</form>
I tried your code. It's working fine. Please try this.
I have written a html form and trying to retrieve the values in node js server.
<form action="/newPost" method="post">
First Name: <br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
var express = require('express');
var bodyParser = require('body-parser');
const hbs = require('hbs');
var {ObjectID} = require('mongodb');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var app = express();
hbs.registerPartials(__dirname + '/views/partials');
app.set('view engine', 'hbs');
app.use(bodyParser.json());
const port = process.env.PORT || 3000;
app.post('/newPost', (req, res) =>{
console.log(req.body.text);
console.log(req.params.firstname);
console.log(req.body.firstname);
res.send(req.body.firstname);
});
expecting mickey but shows undefined
I am using multer module to upload files to my application with a multiform-data enctype on my form. However, I have tried all possible solutions I have found to upload the file in vain. I am receiving always a "Cannot read property path of undefined or file of undefined. Here below is my view, controller and config files, anyone can help point was it wrong?
View
<form method="post" action="/images" enctype="multipart/form-data">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label for="file" class="col-sm-2 control-label">Browse:</label>
<div class="col-md-10">
<input type="file" name="file" id="file" class="form-control">
</div>
</div>
controller:
var tempPath = req.files.path;
var ext = path.extname(req.files.name).toLowerCase();
var finalPath = path.resolve('./public/upload' + imageUrl + ext);
config file:
var path = require('path');
var express = require('express');
var routes = require('./routes'); //routes for GET, POST...requests
var exphbs = require('express-handlebars'); //templating engine
//var bodyParser = require('body-parser'); //form submission request are accessible with req.body
var cookieParser = require('cookie-parser'); //cookies to be send and received
var morgan = require('morgan'); //module for logging - used in debugging
var methodOverride = require('method-override'); //for older browser to fake REST verbs
var errorHandler = require('errorhandler'); //handles error through the middleware
var moment = require('moment'); //npm module to handle dates formating
var multer = require('multer'); //to handle file uploading
module.exports = function(app) {
app.use(morgan('dev'));
//app.use(multer({dest: path.join(__dirname, 'public/upload/temp')})); //proper use of multer
app.use(multer({ dest: path.join(__dirname,'public/upload/temp')}).any());
app.use(methodOverride());
app.use(cookieParser('IciCestParis'));
routes(app); //moving the routes to route folder
app.use('/public/', express.static(path.join(__dirname,'../public')));