Return undefined answer from multer - html

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});
var upload = multer({storage: storage});
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my app.js angularjs code
var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};
And my HTML code:
<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>
On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.

This how i used Multer to upload an image
var multer = require('multer');
exports.loadImage = function (req, res) {
var upload = multer({
inMemory: true,
limits: {fileSize: 1024 * 1024 }
}).single('newPicture');
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({ message: 'errorUploadingPicture' });
}
else {
var profileImage = 'No data uploaded';
// this is where the photo data is
if (req.file && req.file.buffer) {
profileImage = req.file.buffer;
}
return res.json(profileImage );
}
});
};

This is all assuming you are sending your file correct
try
var uploadType = upload.any()
and change
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
to
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});
if you are attempting to only get one file at a time then instead,
var uploadType = upload.single('file')
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});

Related

Nodejs + express + mysql : Wish to create a customer profile page but end up all the path messed up

I will try to describe my question well and what I trying to archieve
I have lots of table like this in my nodejs app
everying member I will give it a href to "/profile/"theirUsername""
after watching ton of tutorial,
I add a button href to my username
$('#pendingDepositTable').append(`
<tr>
<td>
<div class="d-flex align-items-center">
<div class="table-user-name ml-3">
<p class="mb-0 font-weight-medium">`+ response[i].id + `</p>
</div>
</div>
</td>
<td>
<a href="/profile/`+ response[i].customer + `">
`+ response[i].customer + `
</a>
</td>
<td>`+ response[i].bank + `</td>
<td>`+ response[i].amount + `</td>
<td>
<div class="badge badge-inverse-warning"> `+ response[i].status + ` </div>
</td>
<td>`+ response[i].date + `</td>
<td>
<i class="mdi mdi mdi-check-all"></i>
<i class="mdi mdi-close"></i>
</td>
</tr>
`)
}
I add this in my profile.js
router.get('/:id', function (req, res, next) {
console.log(req.params.id);
db.query("SELECT * FROM `customers` WHERE `username` = '" + req.params.id + "'", function (err, result, field) {
try {
res.render('templateMember', { customers_profile: result });
} catch (error) {
console.log(error)
}
})
Before I render the page, I use res.send(result) and get the data that I want successfully.
But all of my header and js script all messed up (I put these in partials.)
and the url all gone wrong
example my transaction page is http://localhost:3000/deposit
but if i redirect from here it become http://localhost:3000/profile/deposit
What can I do or if i miss something?
my projects folder
my app.js
var createError = require('http-errors');
var express = require('express');
var app = express();
var path = require('path');
var session = require('express-session');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var flash = require('express-flash');
app.use(flash());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
var indexRouter = require('./routes/index');
var loginRouter = require('./routes/user_signin');
var memberRouter = require('./routes/members');
var depositRouter = require('./routes/deposit');
var withdrawalRouter = require('./routes/withdrawal');
var creditTransferRouter = require('./routes/creditTransfer');
var cashBonusRouter = require('./routes/cashBonus');
var productListingRouter = require('./routes/products_listing');
var productBalanceRouter = require('./routes/products_balance');
var bankListingRouter = require('./routes/banks_listing');
var bankBalanceRouter = require('./routes/banks_balance');
var bonusRouter = require('./routes/bonus');
var profileRouter = require('./routes/profile')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
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')));
// Login API
app.use('/auth', require('./routes/controllerRoute/auth'));
// Post Product API
app.use('/product_add_action', require('./routes/controllerRoute/product_add_action'));
// Add Member API
app.use('/addMemberRouter', require('./routes/controllerRoute/addMemberRouter'));
app.use('/', indexRouter);
app.use('/userSignin', loginRouter);
app.use('/member', memberRouter);
app.use('/deposit', depositRouter);
app.use('/withdrawal', withdrawalRouter);
app.use('/credittransfer', creditTransferRouter);
app.use('/cashbonus', cashBonusRouter);
app.use('/products_listing', productListingRouter);
app.use('/products_balance', productBalanceRouter);
app.use('/banks_listing', bankListingRouter);
app.use('/banks_balance', bankBalanceRouter);
app.use('/profile', profileRouter);
app.use('/bonus', bonusRouter);
app.all('/', function(req, res){
console.log(req.session)
})
// 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;
Sorry I just found out the answer.
instead of using src="xxx.css"
it should be src="/xxx.css" The leading slash indicates that the request is relative to root not the path that is making the request.
Sorry for post the question without reviewing my code carefully.

node.js formidable with express.js

I am new to node.js and learning it from various sources such as bootcamps, websites, etc.
I want to upload a file using formidable module in node.js and express.js framework. Everytime I run this code it show an error....
var oldpath = file.fileupload.path;
^
TypeError: Cannot read property 'path' of undefined
I have used body parser to receive the name of the file.
Node.js code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var formidable = require("formidable");
var fs = require("fs");
var PORT = process.env.PORT || 5000
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.get("/" , function(req, res){
res.render("form");
});
app.post("/fileupload" , function(req, res){
var fileupload = req.body.filetoupload;
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
var oldpath = files.fileupload.path;
var newpath = "C:/Users/ayush/"+files.fileupload.name;
fs.rename(oldpath, newpath, function(err){
if(err)
console.log(err);
else{
res.write("File Uploaded");
res.end();
}
});
});
});
app.listen(PORT, function(){
console.log("Server started");
});
<!DOCTYPE html>
<html>
<head>
<title>FileUpload</title>
</head>
<body>
<form action="/fileupload" method="POST">
<label>
File:
<input type="file" name="filetoupload" enctype="multipart/form-data">
</label>
<button>Submit</button>
</form>
</body>
</html>
I'm new at this too but the form enctype in form.ejs should be in the <form> tag.
Instead of:
<form action="/fileupload" method="POST">
try:
<form action="/fileupload" method="POST" enctype="multipart/form-data">
You should now have your files object.
Cheers,
Mark
This is a complete working example:
upload.js
'use strict';
const fss = require('fs')
const pth = require('path');
const exp = require('express');
const swg = require('swig');
const efm = require("formidable");
const app = exp();
const thm = swg.compileFile(pth.join(__dirname, '', 'upload.html'));
app.listen(9009);
app.get(`/`, async (q, r) => r.send(thm({ msg: "Select a File to Upload" })));
app.get(`/:msg`, async (q, r) => r.send(thm({ msg: q.params.msg })));
app.post('/upload', (r, q) => {
var form = new efm.IncomingForm();
form.parse(r, (e, p, f) => {
let dir = pth.join(__dirname, '', '/media/');
if (!fss.existsSync(dir)) {
fss.mkdirSync(dir);
}
let nPth = dir + f.file.name;
try {
fss.accessSync(nPth, fss.F_OK);
q.redirect("/File Exists");
} catch (file_e) {
let err = fss.renameSync(f.file.path, nPth);
q.redirect(err ? "/Error" : "/File Uploaded");
}
});
});
You can use fss.access for "A-SYNC" operation.
Its better to use "A-SYNC" functions.
upload.html
<h3>{{msg}}</h3>
<br/>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
fileupload object doesn't exist within file, hence you are getting the undefined error.
To access the old path use :
var oldpath = files.upload.filepath;

sending json data response

I am trying to send a JSON response via HTTP but unfortunately, I don't see any response, I cant understand why really.
It looks like the response variable is not being sent.I am not sure the problem is that it is a JSON object or the way I am sending it.I am new to web development.
The requirement is to help user see the time and the name of the file which was usccessfully sent through.
var express = require('express');
var fs = require('fs');
var cors = require('cors');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'uploads/' });
var Client = require('ssh2').Client;
const request = require('request');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.get('/', function(req, res){
console.log('GET /');
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', upload.single('file'), function(req, res){
var response;
var time;
console.log('POST /');
console.dir(req.body);
// console.log(req.body.filename);
fs.writeFile('./uploads/' + req.body.filename, req.body.file,
function(err) { console.log(err)});
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
// sftp.fastPut('./uploads/' + req.body.filename, '/data/' +
req.body.filename, function (err) {
// if (err) {
// console.log(err);
// throw err;
// }
// });
sftp.readdir('data', function(err, name) {
if (err) throw err;
console.dir(name);
var infoList = JSON.parse(JSON.stringify(name));
for(var index in infoList) {
var value = infoList[index];
time = value.attrs.mtime;
console.log(value.filename);
console.log(time);
response = JSON.stringify(value.filename);
}
conn.end();
});
});
}).connect({
host: 'ftp.amadeus.net',
port: 15022,
username: 'wtl001',
password: 'Wyamp309$'
});
res.writeHead(200, {'Content-Type': 'application/json', "Access-Control-
Allow-Origin": "*"});
res.json(response);
res.end("EOF");
});
port = 12811;
app.listen(port);
console.log('Listening at http://localhost:' + port);

Node.js, how do i take HTML form text input and direct it to a local file

I am trying to take some very simple text input through a form and direct it to a .txt file. not getting much luck and am way out of my depth, any help appreciated.
I have tried a few different ways but atm i am trying to GET the input, turn this into json data and send directly to the file.
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 http = require('http');
var fs = require('fs');
var passport = require('passport');
var passportLocal = require('passport-local');
var expressSession = require('express-session');
var expressValidator = require('express-validator')
//routes setup
var index = require('./routes/index');
var homepage = require('./routes/homepage');
var login = require('./routes/login');
var charitySignUp = require('./routes/charitySignUp');
var about = require('./routes/about');
var contactUs = require('./routes/contactUs');
var charityHomepage = require('./routes/charityHomepage');
var chat = require('./routes/newsFeed');
var ticket = require ('./routes/ticket');
var app = express();
require('./public/configure/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
//app.use(session({secret: 'mySecret', resave: false, saveUninitialized:
false}));
//app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//routes + backend js file
app.use('/', index);
app.use('/login', login);
app.use('/homepage', homepage);
app.use('/charitySignUp', charitySignUp);
app.use('/about', about);
app.use('/contactUs', contactUs);
app.use('/charityHomepage', charityHomepage);
app.use('/chat', chat);
app.use('/ticket', ticket);
/ 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;
Ticket.js - backend code
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function (req, res, next) {
res.render('ticket');
});
router.get('/insert', function (req, res) {
var issue = req.query.issue;
var email = req.query.email;
fs.appendFile("my_file.txt", JSON.stringify(email + issue), function (err) {
if (err) throw err;
console.log('updated');
});
});
module.exports = router;
form in .EJS file.
<form class="form-signin" action="/insert" method="get">
<h2 class ="text" class="form-signin-heading">Ticket form</h2>
<label class="sr-only"><b>email</b></label>
<input type="Email" class="form-control" placeholder="Enter email you would like your response directed" name="email" required>
<label class="sr-only"><b>Issue</b></label>
<input type="text" class="form-control" placeholder="type here" name="issue" required>
<button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</form>

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});