file upload not working in express js using ejs view engine - node.js

I have tried to do file upload in express js project. used ejs as default view engine.
file not uploaded to /uploads folder.
here is my code below.
in app.js file have imported required packages
in routes/index.js route file created route
router.get('/index',indexController.index);
router.post('/insertion',indexController.insertion);
module.exports = router;
in controllers/indexController.js
const multer = require('multer');
const path = require('path');
const storage = multer.diskStorage({
destination:function(req,file,cb)
{
cb(null,'./../uploads');
},
filename:function(req,file,cb)
{
callback(null,file.originalname);
}
});
var upload = multer({storage:storage}).single('resume');
exports.insertion = function(req,res)
{
var file = req.files.resume;
upload(req,res,function(err){
if(err)
{
console.log(err);
}else{
console.log('file uploaded successfully!');
}
});
res.end();
}
in views/registration.ejs file
<form name="registration" action="/insertion" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label>Resume</label>
<input type="file" name="resume" class="form-control" >
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</div>
</form>
file uploading not working .. i need to upload the file under uploads folder which is created in root directory

Related

NodeJS : Multer not saving file

I am working on a project where I need to save a file in a folder,
Here is my relevant code :
<div class="content ui segment" id="two">
<form method="POST" action = "/documents/uploadDoc" enctype="multipart/form-data">
<h2>Upload new file</h2>
<br>
<input class='button' type="file" id="myFile" name="filename">
<input type="submit" name = "Submit">
</form>
</div>
My multer code :
var multer = require('multer');
const fileStorage = multer.diskStorage({
destination : (req,file,cb) => {
cb(null,'tempSave/');
},
filename : (req,file,cb) => {
cb(null,file.originalname)
}
})
const saveFile = multer({ storage : fileStorage});
And my router :
router.post("/uploadDoc", saveFile.single('filename') ,function(req,res,next){
console.log("Uploading");
console.log(req.body);
var fileName = req.body.filename;
console.log(fileName);
});
There isn't any error, but the file is not getting saved in the required place. Please help
Can you check do you have tempSave folder in the root of your server directory? If not, create it and try it again.

Form submit with bootstrap and nodejs

I am using boostrap (via MDB 4) and am trying to get the contact form to work. I have the form presenting as expected. It contains the following button outside the </form> tag
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
The opening line of the form is:
<form id="contact-form" name="contact-form" action="/contact" method="POST">
I am trying to understand how I get the form contents to nodejs and have the following in my Express routes
app.post('/contact', function(req, res){
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.subject);
console.log(req.body.message);
// code to store here later
});
I know this I am hitting this block as I can console out text from within the route but I get an error every time:
TypeError: Cannot read property 'name' of undefined
All the examples seem to use PHP but I would have thought nodejs would be more than enough for this? I don't have PHP on the box and would rather avoid it if I can stay in nodejs. Anyone got some pointers for me?
It might be worth noting that jquery is used but I don't know if that links in here? The following is at the foot of my html
<script type="text/javascript" src="js/jquery.min.js"></script>
Solved by adding the following to my index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
Now when I console.log(req.body); is get:
{
name: 'name',
email: 'name#x.y',
subject: 'test',
message: 'test'
}
I created solution for you:
//connect express
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var partials = require('express-partials');
var app = express();
app.use(express.json());
app.use(partials());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
//top level routing
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.post('/contact', function(req, res){
res.render('thanks.ejs', {body: req.body})
});
//start server
var http = require('http');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
<!--- start index.ejs -->
<form action="/contact" method="post" class="form-signin">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" placeholder="Enter subject">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea type="text" class="form-control" name="message" placeholder="Enter message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--- end index.ejs -->
<!--- start thanks.ejs--->
<%=JSON.stringify(body)%>
<!--end thanks.ejs --->
<!--- start layout.ejs --->
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content">
<%-body -%>
</div>
</div>
</body>
</html>
<!--- end layout.ejs --->
My answer is based on this resource https://exceed-team.com/tech/form-submit-with-bootstrap-and-nodejs

'cannot get addfriend' in express while using postrequest

This is my code app.js code
var express = require("express");
var app = express();
var bp = require("body-parser");
app.use(bp.urlencoded({extended: true}));
var friends = ["babba","lkshjk","kfhkd"];
app.get("/",function(req,res){
res.send("homepage");
});
app.get("/friends",function(req,res){
res.render("friends.ejs",{friends : friends});
});
app.post("/addfriends",function(req,res){
res.send("works fine");
});
var server = app.listen(2700 ,function() {
console.log("started");
});
and this is friends.ejs code
<h1>
friends list
</h1>
<% friends.forEach(function(friend){ %>
<li> <%= friend %> </li>
<% }); %>
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
i just need "works fine " in my '/addfriend'
but i am getting
cannot get /addfriend in chrome
this works fine in postman when i try to debug
Your form have to point to the express route.
It should be:
<form action="/addfriends" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
Instead of
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
You should declare your route equal you did in express route:
app.post("/addfriends",function(req,res){
res.send("works fine");
});

app.post and the express-fileupload dependency is producing no response

I have a simple html uploading form
<h1>Upload File Here</h1>
<form methods="post" enctype="multipart/form-data" action="/">
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
I want uploaded files to hit a "/upload" folder. I am using the following express code to do this.
const express = require("express");
const app = express();
upload = require("express-fileupload");
app.listen(80);
app.use(upload());
console.log("Server Started");
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/", (req, res) => {
if (req.files) {
var file = req.files.filename,
filename = file.name;
file.mv("/upload/" + filename, err => {
if (err) {
console.log(err);
res.send("error occured");
} else {
res.send("done!");
}
});
}
});
When I start the server and go to localhost in Chrome, I see the upload form. If I try to upload something, the url box changes to reflect the file I tried to upload, but the file does not appear in the '/upload' folder. Any ideas on what obvious mistake I'm making??
Thanks!
The solution is in my form. I need to set the action="http://localhost:80/upload"
New HTML is
<h1>Upload File Here</h1>
<form
ref="uploadForm"
id="uploadForm"
action="http://localhost:80/upload"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>
The solution is in my form. I need to set the
action="http://localhost:80/upload"
New HTML is
<h1>Upload File Here</h1>
<form
ref="uploadForm"
id="uploadForm"
action="http://localhost:80/upload"
method="post"
enctype="multipart/form-data"
>
<input type="file" name="filename" /> <input type="submit" value="upload" />
</form>

Node.js uploaded file does not have path property

I am writing a file upload demo by multer in node.js.When form submit, I can get the file information, but it does not have path property.
ejs file
<form method="post" enctype="multipart/form-data">
<p>
<input type="text" name="name" placeholder="name">
</p>
<p>
<input type="file" name="photo">
</p>
<p>
<input type="submit" value="Upload">
</p>
</form>
js
function (req, res ,next) {
var img = req.file;
var name = req.body.name || img.originalname;
var path = require('path').join(dir, name);
console.log(img);
}
multer config
var multer = require('multer')();
app.post('/upload',multer.single('photo'),photos.submit(app.get('photos')));
req.file
You are using memStorage for storing file. That's why there is no path in req.file. Try changing this to: var upload = multer({ dest: 'uploads/' }). Replace uploads/ with directory where you want to upload your file.

Resources