Error uploading image using node.js - Express - javascript

Im testing examples of Express but i have problems with this one.
I'm trying to execute this code example (example taken from the web) and i having this error when i try to upload an image.
TypeError: Cannot read property 'file' of undefined
SERVER
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var multer = require('multer');
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
CLIENT
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>

Try this...
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="foo" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
Server.js
var express = require('express');
var app = express();
var path = require("path");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
var upload = multer({
dest: path.join(__dirname, '../public/upload/temp')
});
app.post('/file_upload', upload.single('foo'), function(req, res) {
if (req.file) {
console.dir(req.file);
return res.end('Uploaded successfuly');
}
res.end('No file found');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
For multi upload change upload.single('foo') to upload.array('foo')

Related

Form inputs not retrievable using bodyParser and Router()

I am trying to create a registration form which will pass data to the registration route. However, I am having trouble retrieve the form inputs in registration route. Please advice how to retrieve the form data inside the api.js file. I have tried using POSTMAN to send data to the /api/registration endpoint which did create a user in the database. When I actually use the html form to register, it failed.
HTML
<!DOCTYPE html>
<html>
<body>
<form action="/api/register" enctype="multipart/form-data" method="post">
<input name="email" type="text" placeholder="Email">
<input name="password" type="password" placeholder="Password">
<input name="passwordConf" type="password" placeholder="Confirm Password">
<input type="submit" value="Register">
</form>
</body>
</html>
Index.js
//----setting up modules
const express = require('express');
const hbs = require('hbs');
const path = require('path');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/test');
//----define port connection on various environmentls
const port = process.env.PORT || 3000;
//----createing express app
var app = express();
// parse incoming requests
app.use(bodyParser.json());
//----use express middle-ware to utitlize public folder
// app.use(express.static(__dirname + 'public'));
app.use('/public', express.static(path.join(__dirname,'public')));
//see the first argument in above line it assigns which directory path is used to access the public file through URL
//----initializing handlebars as express view engine
app.set('view engine', 'hbs');
//----define handlebars partials and helpers
hbs.registerPartials(__dirname + '/views/partials');
//----define helper to get current year
hbs.registerHelper('getDate', ()=>{
return new Date().getFullYear();
});
//----define routes
app.get('/', function (req, res) {
res.render('home.hbs')
})
// include routes
app.use('/api', require('./routes/api'));
app.use('/', require('./routes/page'));
//----connecting to port
app.listen(port,()=>{
console.log(`success connection to port ${port}`);
})
Api.js Route
var express = require('express');
var router = express.Router();
var {User} = require('./../models/user');
var {authenticate} = require('./../middleware/authenticate');
var _ = require('lodash');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
router.post('/register',function (req, res) {
console.log(req.body);
});
module.exports = router;
pages.js
var express = require('express');
var router = express.Router();
router.get('/register', function (req, res) {
res.render('register.hbs', {title:"REGISTER"} )
})
router.get('/login', function (req, res) {
res.render('login.hbs', {title:"LOGIN"} )
})
module.exports = router;
Here is my recommendation:
Create a file called routes.js and include ALL your routes there and import it.
var express = require('express');
var router = express.Router();
app.get('/', function (req, res) {
res.render('home.hbs')
})
router.get('/api/register', function (req, res) {
res.render('register.hbs', {title:"REGISTER"} )
})
router.post('/api/register',function (req, res) {
//do your post logic here
console.log(req.body);
});
router.get('/login', function (req, res) {
res.render('login.hbs', {title:"LOGIN"} )
})
module.exports = router;
in your Index.js :
//Make sure the route is correct
app.use('/', require('/routes/routes.js'));
Doing this, I expect the error to be solved,
Good luck!

How to get file extension in node js using formidable?

My Code:
Js File:
var formidable = require('formidable');
var fs = require('fs');
var ex = require('express');
var fse = require('fs-extra');
var app = ex();
app.set('view engine', 'ejs');
app.get('/form', function(req, res) {
res.render(__dirname + '/views/front.ejs', {title: 'form-page'});
}).listen(8081);
app.post('/form', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.fil.path;
var newpath = __dirname + '/uploads/' + files.fil.name;
var fileExt = files.fil.name.split('.').pop();
fse.move (oldpath, newpath, function (err) {
if (err) { throw err; }
});
});
});
Html/Ejs File:
<html>
<title> <%= title %> </title>
<body>
<h2> Form </h2>
<form action="/form" method="post" enctype="multipart/form-data">
Name: <input type="text" name="name" /><br>
File: <input type="file" name="fil" />
<input type="submit" value="Submit">
</form>
</body>
</html>
all the packages are properly installed and with this code, files(with any extension) are getting uploaded to the desired directory properly.
What i want is for only image files to be uploaded ex:- jpeg,png etc
Thank you.
Use this code:
form.onPart = function (part) {
if(!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) {
this.handlePart(part);
}
else {
console.log(part.filename + ' is not allowed');
}
}
Source: uploading files using express.js and node, limiting extensions

files upload using express 4.15 not working

I'm using express for the first time, and got some problem while uploading files. I've followed many tutorials but no one worked. I just got an empty page and no file is uploaded
index1.jade
doctype html
html(lang='en')
head
title
meta(charset='UTF-8')
body
form(role="form", action="/", method="post", enctype="multipart/form-data")
div(class="form-group")
label(for="onixfile") Upload ONIX File
input(type="file", name="onixfile", id="onixfile")
input(type="submit")
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var multer = require('multer');
var app = express();
var multer = require('multer');
var upload = multer({ dest: './uploads' });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
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;
route/index.js
var express = require('express');
var multer = require('multer');
var router = express.Router();
var upload = multer({ dest: 'uploads/' });
/* GET home page. */
router.get('/', function(req, res) {
res.render('index1', { title: 'ONIX Validator' });
});
router.post('/upload', upload.single('file'), function(req, res){
var file = '/' + req.file.filename;
var fs = require('fs');
fs.open("./uploads",'r',function(err, fd){
fs.readFile(file ,function(err, data){
if(err) throw err;
fs.writeFile("./uploads/"+req.file.filename, data), function(err) {
if(err) {
console.log(err);
}else {
console.log("Done");
}
}
});
});
});
module.exports = router;
Do this in your route/index.js
var upload = multer({ dest: 'uploads/' });
router.post('/upload', upload.single('file'), function(req, res){
var file = '/' + req.file.filename;
var fs = require('fs');
fs.open("./uploads",'r',function(err, fd){
fs.readFile(file ,function(err, data){
if(err) throw err;
fs.writeFile("./uploads/"+req.file.filename, data), function(err) {
if(err) {
console.log(err);
}else {
console.log("Done");
}
}
});
});
});
This should upload the file to your applications file-system in the /uploads dir.
Make sure you have to place these html & js file into uploads folder in solution directory.check it out below code.
Index.html Code:
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/photo"
method = "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" id="upload" name="submit">
</form>
Server.js Code:
var express = require("express");
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
var splitted = file.originalname.split('.');
var format = splitted[splitted.length - 1];
callback(null, file.fieldname + '-' + Date.now() + '.' + format);
}
});
var upload = multer({ storage: storage }).single('userPhoto');
app.get('/', function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post('/api/photo', function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end("Error uploading file.");
}
res.send("File is uploaded");
});
});
app.listen(3000, function () {
console.log("Working on port 3000");
});

Uploading images using Express

I am building an REST Api where it contains quite a few images using Express. The project structure is shown below.
And inside the public folder you can see that structure.
I want to upload images and store them inside the img folder. So here is my code.
fileupload.html
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:3000/fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
and fileupload.js
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
//console.log(multer);
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/img'}));
app.get('fileupload.html', function (req, res) {
res.sendFile( __dirname + "/" + "fileupload.html" );
})
app.post('/fileupload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/img" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at localhost:3000/", host, port)
})
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/larissaApp';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error:'));
db.once('open',function(){
console.log("Connected correctly to server");
});
var routes = require('./routes/index');
var users = require('./routes/users');
var newsRouter = require('./routes/newsRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use( bodyParser.json({limit: '50mb'}) );
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit:50000
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/news',newsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
However after trying to upload an image from the html page,I get a 404 error.
404
Error: Not Found
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\app.js:40:13
at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:275:10)
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:635:15
at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:260:14)
at Function.handle (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:275:10)
at serveStatic (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\serve-static\index.js:75:16)
What am I doing wrong?
Thanks,
Theo.
Download the code for Uploading images using Express
File upload with express
Try this.
I modified your js little bit, it works for me without errors.
I've written comments for each line edited.
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');
//console.log(multer);
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
var upload = multer({dest: './img'});// declare multer default path(best to use /tmp for this if on linux)
app.get('fileupload.html', function (req, res) {
res.sendFile(__dirname + "/" + "fileupload.html");
});
app.post('/fileupload', upload.single('file')/*inserted multer middleware for one file*/, function (req, res) {
//Declare variable to easy change
var file = req.file;
// this are correct names for variables of req.file
console.log(file.filename);
console.log(file.path);
console.log(file.mimetype);
// path of file stored
var path = __dirname + '/img/';
// variable for storing path
var filePath = path + file.filename;
//It's better to declare variable first then use it
var response;
fs.readFile(filePath, function (err, data) {
fs.writeFile(path + file.originalname, data, function (err) {
if (err) {
console.log(err);
} else {
response = {
message: 'File uploaded successfully',
filename: file.originalname
};
}
console.log(response);
res.end(JSON.stringify(response));
});
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at localhost:3000/", host, port)
});

Why can't I upload a file?

I'm trying to upload a photo using Node.js. But when I upload, it shows this error:
Cannnot read property file of undefined
at C:\new\file.js:13:26
Looks like I'm doing something wrong with req.files.file.name which I don't understand. What can be the issue?
Here's the code:
file.js
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: '/files/'}).single('file'));
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + '/' + '/index.html')
});
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + '/' + req.files.file.name;
fs.readFile(req.files.file.name, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log("Error reading");
} else {
response = {
message: 'file uploaded successfully',
filename: req.files.file.name
};
}
console.log(response);
res.end(JSON.stringify(response));
});
});
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("The server is running at http://%s:%s ", host, port);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8081/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
</form>
</body>
</html>
Here's what I do, which works fine:
var uploadPath = 'public/uploads/';
var upload = multer({dest: uploadPath});
router.post('/image', upload.single('thePhoto'), function (req, res) {
var uploadedFile = uploadPath + req.file.filename;
The problem can be caused because you have already added multer in app.use() which parses all the data before the control goes to post method. So I think you should either use fs or multer but not both.

Categories

Resources