Uploading images using Express - javascript

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)
});

Related

multer upload returns 500 with python post

I am trying to upload a single image using python code to a node js express server. The python code is:
import requests
url = 'http://localhost:9000/testAPI/uploadphoto'
files = {'file': ('photo', open('test.jpg', 'rb'))}
ret = requests.post(url, files=files)
print ret
For the app.js, it is mostly following the default template:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser= require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
and I am using the router testAPI for handling the POST:
var express = require('express');
var multer = require('multer');
var router = express.Router();
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
var filename = file.originalname;
var fileExtension = filename.split(".")[1];
cb(null, Date.now() + "_" + filename);
}
});
var upload = multer({ storage: storage });
router.get('/', function(req, res, next) {
console.log("test");
res.send('API is working properly');
});
router.post('/uploadphoto', upload.single('photo', (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send('Photo uploaded');
}));
module.exports = router;
When I run the python code, the server returns 500. In my node js directory, I have an uploads folder created.
At the first you should run your node server project in port 9000
Your npm start probably calls your bin/www file. Which contains the listen invocation to start your app.
Many people set up their app this way. eg. app.js to define and configure their app, and something like bin/www to actual get the server running. This way they can include the app.js into other parts, say tests, without actually starting the server when you require it.
Figured it out. Since my server is started in the bin/www file as opposed to the app.js file, from the terminal I went into my bin directory and then called
node wwww
or
nodemon www
or add this code to the app.js and then run it with node app.js to listen port 9000
const port = 9000;
app.listen(port, () => console.log(Example app listening on port ${port}!))

req.body undefined multipart

I have a problem with my POST request on multipart (form-data). All ideas in other topics don't work.
I use express, multer and postman
I totally delete body-parser
Uploading files works but accessing the data with a key don't work.
When I try console.log(req.body); I obtain undefined
This is my code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cors=require('cors');
//var index = require('./routes/index');
//var users = require('./routes/users');
var UsersDB=require('./routes/UsersDB');
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(cors());
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
//app.use('/users', users);
app.use('/Users',UsersDB);
// 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;
UsersDB.js
var express = require('express');
var router = express.Router();
var Users=require('../models/Users');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + ".png")
}
});
var upload = multer({ storage: storage }).single('avatar');
//** POST ** ROUTE : http://localhost:3000/Users/
router.post('/',function(req,res,next)
{
console.log(req.body.firstName);
/*
Users.addUsers(req.body,function(err,count)
{
if(err)
{
res.json(err);
}
else
{
res.json(req.body);//or return count for 1 &amp;amp; 0
}
});
*/
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
return
}
// Everything went fine
})
});
module.exports=router;
Error on Postman:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Cannot read property 'firstName' of undefined</h1>
<h2></h2>
<pre>TypeError: Cannot read property 'firstName' of undefined
at /mnt/c/Users/Elodie/Desktop/server/routes/UsersDB.js:69:25
at Layer.handle [as handle_request] (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at next (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at /mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:335:12)
at next (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:174:3)
at router (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:47:12)</pre>
</body>
</html>
Since you're using multer to parse the request body, you're going to need to invoke multer prior to accessing req.body. The way you are currently using multer, it will extract the information from the request to process the file but will not be part of the middleware stack so you don't get the benefit of the body parsing prior to your route being called.
Add the multer middleware into the route signature and so it the request body will be parsed by multer prior to the route callback being invoked. For example like this
router.post('/', upload.single('avatar'), (req, res, next) => {
console.log(req.body.firstName)
})

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");
});

Connection between 2 different servers Express.js and node js

I have a Experss.js framework and Node.js with a request to MS SQL database on the server side.
I want to get a data(in JSON or array) from server and send to Cliend side.
I don't understand how can I write routers for another server on the Client side.
server.js
npm start
http://localhost:5000/
Code:
var sql = require("mssql");
var express = require('express');
var app = express();
var http = require('http')
var query = "SELECT AVG([sta_waittime]) AS Spalte FROM [DialogMaster_TEST].[dwh].[anruf_stat] WHERE CONVERT(DATE,sta_timestamp) = CONVERT(DATE,CONVERT(DATE,'2016-08-01')) ";
app.get('/', function (req, res) {
sql.connect("mssql://log:pas#db/TEST").then(function() {
// Query
new sql.Request().query(query).then(function(recordset) {
var a = [];
a.push(recordset[0].Spalte);
res.send(a); // **number**
}).catch(function(err) {
// ... query error checks
});
}).catch(function(err) {
// ... connect error checks
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Server site in Browser:
My app.js file.
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 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')));
app.use('/', routes);
app.use('/users', users);
//app.get('/');
// 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 need only 1 server(REST server). Just use node.js server.
Read it:
REST

NodeJS - get property for Mongodb not working while connecting

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.

Categories

Resources