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");
});
Related
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)
});
I am trying to design a simple app to upload files to a server. The front-end uses AngularJS in a Jade view engine, the back-end is an Express server written in Nodejs.
I am using ng-file-upload, but the problem is that the Upload service provided by the file upload module requires a Url destination for the file to be uploaded at. No matter what I place in this destination, my app gives me a 404 error of not found. I have no idea how to provide a destination folder to ng-file-upload in a way that doesn't generate a 404 error.
Here is my controller for the upload:
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function($scope, Upload, $timeout) {
$scope.uploadFiles = function(file, errFiles) {
$scope.f = file; //set the global scope file to 'file'
$scope.errFile = errFiles & errFiles[0]; //check if any invalid filed exist
if (file) { //check if a file was submitted
file.upload = Upload.upload({
url: 'http://localhost:3000/upload',
data: { file: file }
});
file.upload.then(
function(response) {
$timeout(function () {
file.result = response.data;
});
},
function(response) {
if (response.status > 0) {
$scope.errorMsg = response.status + ': ' + response.data;
}
},
function(evt) {
file.progress = Math.min(100, parseInt(100.0 * (evt.loaded / evt.total)));
}
);
}
}
}]);
Here is my jade template:
extends layout
block content
h1= title
button(type='file', ngf-select='uploadFiles($file, $invalidFiles)', accept='.csv')
| Select File to Upload
br
br
| File:
div(style='font:smaller')
| {{f.name}} {{errFile.name}} {{errFile.$error}} {{errFile.$errorParam}}
span.progress(ng-show='f.progress >= 0')
div(style='width:{{f.progress}}%', ng-bind="f.progress + '%'")
And my express server app.js, which includes multer as middleware:
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 multer = require('multer');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb (null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb (null, (file.originalname + 'datetimestamp'));
}
});
var upload = multer({ storage: storage }).any();
// 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(function(req, res, next) {
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "http://localhost");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});*/
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('/bower_components', express.static(path.join(__dirname, 'bower_components')));
app.use(express.static('../client'));
app.use('/', routes);
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 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: {}
});
});
app.post('/upload', function (req, res) {
upload(req, res, function(err) {
if (err) {
res.json({ error_code: 1, err_desc: err });
return;
}
res.json({ error_code: 0, err_desc: null });
});
});
module.exports = app;
Any idea how to give the angular module a server-side folder it can store the file in?
lately i started to play around with express.js the nodejs web framework. i'm making a simple form that send data to a express route.
I have a users.js route file and inside that there is a register route.
my user.js route file
router.post('/register', function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var passwordConfirm = req.body.passwordConfirm;
console.log(name);
my jade file which form is in it
form(method='post',action='/users/register',enctype='multipart/form-data')
.form-group
label Name
input.form-control(name='name',type='text',placeholder='Enter Name')
and go on ...
console.log retunrs undefiend.
my app.js . I used express generator to generate project, as you can see i have multer and bodyparser
var bodyParser = require('body-parser');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// multer config inja
var upload = multer({ dest: './uploads' });
// 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 }));
// // handle express session
app.use(session({
secret: 'secret', //encryption key
saveUninitialized:true,
resave:true
}));
// // Passport
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// flash messaging via connect-flash
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
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 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;
You have to configure an express middleware to parse the body of your HTTP request before hitting your /register route.
multipart/form-data enctype
This kind of type is often use for file upload. A library like Multer can be helpful for this use case.
I don't see a file to upload in your example. So you should consider using a simple enctype like application/x-www-form-urlencoded enctype (default) (see below).
If you still want to use form-data enctype without file upload, you can use a library like express-busboy (built on top of busboy).
var app = express();
var bb = require('express-busboy');
bb.extend(app);
// ...
router.post('/register', function(req, res, next) {
// req.body contains your fields.
// ...
application/x-www-form-urlencoded enctype (default)
If you configure your form to use the application/x-www-form-urlencoded enctype, it's a little bit easier to handle in your route.
body-parser can be use as a middleware too: https://github.com/expressjs/body-parser#bodyparserurlencodedoptions
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());
// ...
router.post('/register', function(req, res, next) {
// ...
```
I'm starting to learn Node and Express, but I currently can't get some of my routes to work.. Here's the app.js file that I'm currently using
EDIT: Here's my updated files, but I stil get a 404
var db = require('./db');
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 session = require('express-session');
var routes = require('./routes/index');
var users = require('./routes/users');
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());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
//res.send(req.path)
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;
And the route I can't view is '/users/userlist' here is my userlist.js route
EDIT: I've moved '/users/userlist' into the users.js route
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');
/* GET users listing. */
router.get('/users/add/*:', function(req, res, next) {
var params = req.params[0].split("/");
if(params.length>=2){
var newUser = new User({username: params[0], password:params[1]});
newUser.save(function(err, fluffy){
if(err)
res.send(err);
});
}
res.send('Account Created!');
});
router.get('/users/userlist', function(req, res) {
var users;
User.find(function(err, _users){
if(err)
users="ERROR";
else
users=_users;
});
res.send(users);
});
module.exports = router;
When I try and point my browser to http://localhost:3000/users/userlist I just get a 404.
You have made a mistake while declaring routes in app.js,remove below code.
app.use('/users/userlist',userlist);
I am new to NodeJS and ExpressJS. I am following this tutorial http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ for creating and connecting mongodb with nodejs. Everything works perfectly(DB data inserting through command line,package.json config) except db connection, it throws undefined error.
var monk = require('monk');
var db = monk('localhost:27017/deno');
I check this in console like this console.log(db) it shows 'undefined' in index.js
My app.js is :
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');
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Fujitsu');
var routes = require('./routes/index');
var users = require('./routes/users');
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());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', routes);
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 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;
routes/index.js is
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/************ Customized starts Here **********/
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
console.log(db);
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
/******** Customized - Ends here ***********/
module.exports = router;
Please anyone of you tell me the solution because now I'm struggling with this.
Thanks In Advance.