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')));
Related
How do I post a value which is on the client-side and get it on the server-side.
example:
<form action="/myform" method="POST">
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.get('/myform', function(req, res){
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
app.listen(3000)
<form action="http://127.0.0.1:3000/myform" method="post">
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myform', function(req, res) {
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
Your code seems to be fine, apart from wrong method name. In HTML form you have mentioned POST method but at server you are listening to GET method. So just change, app.get('/myform', to app.post('/myform',.
It should work.
I want to send a file with express-busboy. On the readme it says that you can use req.body. So i did. The regular inputs worked, but the file inputs just returned the name of the file i uploaded. I uploaded the file called myfile.png and in the textinput, i put the value of 'Hello World'. I want the send the file that i upload to a folder called mydir (which is in ./). Here is a sample of code:
//js:
const express = require('express');
const mysql = require('mysql');
const bp = require('body-parser');
const session = require('express-session');
const uc = require('upper-case');
const busboy = require('express-busboy');
const fs = require('fs');
const util = require('util');
const app = express();
app.use(bp.urlencoded({ extended: true }));
busboy.extend(app, {
upload: true,
path: './mydir'
});
app.post('/somewhere', (req, res) => {
console.log(req.body.textinput);
//returns the 'Hello World'
console.log(req.body.imginput);
//returns 'myfile.png'
});
<html>
<body>
<form action="/somewhere" method="post" enctype="multipart/form-data">
<input type="text" name="textinput">
<input type="file" name="imginput" accept='image/*'>
</form>
</body>
</html>
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'm trying a simple form submission code, and I'm using post method.
My server.js code
//N-4E;V-56;I-49
//var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var idx = require('./index.js');
var ra = require('./ra.js');
var app = express();
app.engine('html',require('ejs').renderFile);
app.set('view engine', 'html');
app.set('port',process.env.PORT || 5649);
app.use(bodyParser.urlencoded({extended: true}));
app.use('/',idx);
app.use('/reg_path',ra);
app.listen(app.get('port'),function(){
console.log('Express started press asdfadsfasdfasdf');
});
my index.js
var express = require('express');
var fs = require('fs');
var router = express.Router();
router.get('/',function(req,res,next){
//res.sendHeader(.)
res.render('index.ejs',{});
//res.render('title.ejs',{});
});
module.exports = router;
my index.ejs
<!DOCTYPE html>
<html>
<head>
</head>
</body>
<div id="reg_path">
<p>Enter the Regressions Folder Path</p>
<form action="/reg_path" method="post" enctype="multipart/form-data">
<fieldset>
<label for="path">Path:</label>
<input type="text" id="path" name="path" placeholder="Enter the Absolute path"/>
<input type="submit" value="Enter"/>
</fieldset>
</form>
</div>
</body>
</html>
my ra.js is
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express.Router();
var path;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post("/",function(req,res){
console.log(req.body.path);
path = req.body.path;
fs.access('path',fs.constants.F_OK, (err) => {
if (err) throw err;
res.redirect('./index');
//if (err) {
// res.writeHead(404,{'Content-Type':'text/plain'});
// return res.end('The specified path "' + path + '" does not exists');
//}
});
//fs.access('path',fs.constants.R_OK, (err) => {
// //if (err) {
// // res.writeHead(404,{'Content-Type':'text/plain'});
// // return res.end('The specified path "' + path + '" has no READ permissions');
// //}
//});
});
module.exports = app;
Now, from the index page, when I type a path in the form, and press the submit, in the console.log the 'req.body' is returned as 'undefined'.
most of the code in ra.js is commented or not updated because the 'req.body' value is unavailable in the first place. I need to correct it first.
I've searched through internet to try and figure out the mistake that is in my code, but to my vain I'm unable to uncover it. Any help is much appreciated
node version:v6.11.0
body-parser :1.17.2
express :4.15.3
ejs :2.5.6
Your form uses enctype="multipart/form-data" which is an encoding type that body-parser doesn't support.
If you need to use this type (for instance, if you're going to be uploading files from your form), take a look at multer.
Otherwise, leave out the enctype attribute so the form will default to application/x-www-form-urlencoded.
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"});
});
});
})