How to upload images on node js? - javascript

I am having issues getting any image data on the form in the ejs file after submitting. Upon debugging, there is a req.body.image which has the filename but req.file is undefined. I have tried many sites online detailing how to upload images but none seem to be working, any suggestions?
Part of the code in server.js file:
require("dotenv").config()
const express = require("express");
const cors = require("cors");
const path = require('path')
const app = express();
const mongoose = require("mongoose")
const fs = require('fs')
const multer = require('multer')
const fileupload = require("express-fileupload");
const Grid = require("gridfs-stream");
let gfs;
app.use(fileupload());
require('./routes/auth.routes')(app);
require('./routes/user.routes')(app);
app.use('/uploads', express.static('uploads'))
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
app.use(cors(corsOptions));
app.use(express.json());
var storage = multer.diskStorage({
destination: function(req,file,cb){
cb(null, '../uploads/')
},
filename: function(req, file, cb) {
cb(null, Date.now()+file.originalname)
}
})
const fileFilter = (req,res,cb) =>{
if(file.mimetype === "image/jpeg"||file.mimetype ==='image/png'){
cb(null, true);
}else{
cb(null,false);
}
}
var upload = multer({
storage:storage,
fileFilter: fileFilter
})
app.post('/makepost', upload.single('image'), async function(req, res, next){
if(req.file)
{
const pathName=req.file.path;
res.send(req.file.filename)
}
await db.post.create({
"author": "",
"title": req.body.title,
"img": req.file,
"description": req.body.description
})
res.render('pages/index', {loggedin: loggedin, test: test});
});
createpost.ejs page:
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../partials/head'); %>
</head>
<body class="u-body u-xl-mode"><div class="u-clearfix u-sheet u-valign-middle u-sheet-1">
<%- include('../partials/navbar', {loggedin:loggedin}); %>
<section>
<h1 align="center">Create post</h1>
</section>
<div class="createpost">
<form action="/makepost" method="post">
<label for="title">
<!-- font awesome icon -->
<i class="fab fa-adversal"></i>
</label>
<input type="text" name="title" placeholder="Title" id="title" required>
<br>
<label for="description">
<i class="fa fa-paper-plane"></i>
</label>
<input type="text" name="description" placeholder="Description" id="description" required>
<br>
<label for="image">Upload Image</label>
<input type="file" id="image" name="image" required>
<input type="submit" value="Upload post">
</form>
</div>
</div>
<footer>
<%- include('../partials/footer'); %>
</footer>
</body>
</html>

Add enctype='multipart/form-data' attr to the form.
Whenever you have files inside a form it is required that you have this.
example:
<form action="/makepost" method="post" enctype="multipart/form-data">
...
</form>

Related

express post method and body.req does not work

I am trying to get "POST" method form data from HTML form using app.post method but I can catch anything to req.body. What am I doing wrong?
My html form -
<form method="POST" action="/success.html">
<div id="input-area">
<textarea id="title" name="title" rows="1" cols="75" placeholder="Title" onkeyup="instance.tweaker()"></textarea>
<textarea rows="10" type="text" cols="75" placeholder="Description" name="description"></textarea>
<div id="calender"><input id="dater" type="date" value=""></div>
<button type="submit" value="Submit" id="buton">Add Task</button>
</div>
</form>
<script src="backend2.js" defer></script>
my js code
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.listen(3308,() =>{
console.log('My server is running');
})
const jsonParser = bodyParser.json();
//
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/success.html', urlencodedParser , function (req, res) {
console.log(req.body.title);
})
I reproduced your code without any error. To test it quickly, i send the index.html as the default route.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const port = 3308;
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.post('/success.html', urlencodedParser, (req, res) => {
res.send(req.body.title);
});
app.listen(port, () => {
console.info(`server running on port ${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Upload Example</title>
</head>
<body>
<form method="POST" action="/success.html">
<div id="input-area">
<textarea
id="title"
name="title"
rows="1"
cols="75"
placeholder="Title"
onkeyup="removedForExample"
></textarea>
<textarea
rows="10"
type="text"
cols="75"
placeholder="Description"
name="description"
></textarea>
<div id="calender"><input id="dater" type="date" value="" /></div>
<button type="submit" value="Submit" id="buton">Add Task</button>
</div>
</form>
</body>
</html>
First of all, I am not sure which version of Express you are using but if you are using version 4.0 or up, you don't really need to import body-parser separately.
Also, you may re-order the code. Why don't you try like this?
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/success.html', urlencodedParser , function (req, res) {
console.log(req.body.title);
})
app.listen(3308,() =>{
console.log('My server is running');
})

Node.js express: trying to get text from HTML form, req.body empty

I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>index.html</title>
</head>
<body>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
</body>
</html>
app.js
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const configRoutes = require("./routes");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
configRoutes(app);
app.listen(3000, () => {
console.log("Speech Server");
});
index.js
const express = require("express");
const speakRoutes = require("./speak");
const constructorMethod = (app) => {
app.use("/speak",speakRoutes);
app.use("*", (req,res) => {
res.sendFile("index.html", { root: "./public" });
});
};
module.exports = constructorMethod;
speak.js
const express = require("express");
const router = express.Router();
router.post("/", async (req,res) => {
console.log("POST");
console.log(req.body);
res.sendFile("index.html", { root: "./public" });
});
module.exports = router;
I would greatly appreciate some help! Thank you!
Your input has no name, give your input a name so you know what property to look for in the form:
<input type="text" id="text-box" name="whatever" ... />
EDIT: A client-only example. One field has a name.
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(e.currentTarget).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!" name="whatever" />
<input type="text" id="text-box" title="text" placeholder="I have no name so I won't be sent!" />
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
I fixed my own issue! It worked by changing post to get in the route and the html form method, and req.body to req.query

Cannot read property 'path' of undefined node js multer

i am building a app that lets the user create a camp and than edit it.Recently i added the upload image feature it works fine with the create route but on the edit one it doesnt let the user leave it blank cause if that happens it give the undefined error.Do you have anyideas how i can fix this.I dont have much experience so any help would be welcomed.
This is the js code
var express = require("express");
var router = express.Router({mergeParams:true});
var Campground = require("../models/campground");
var middleware=require("../middleware");
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/');
},
filename: function(req, file, cb) {
const now = new Date().toISOString(); const date = now.replace(/:/g, '-'); cb(null, date + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
//edit
router.get("/:id/edit",middleware.checkCampgroundOwnership, function(req,res){
Campground.findById(req.params.id,function(err,foundCampground){
res.render("campgrounds/edit",{campground :foundCampground});
});
});
router.put("/:id",upload.single('image'),middleware.checkCampgroundOwnership, function(req,res){
var name = req.body.name;
var image = req.file.path;
var description = req.body.description;
var price = req.body.price
var upCampground = {price:price,name:name, image: image ,description:description};
Campground.findByIdAndUpdate(req.params.id,upCampground,function(err,updatedCamp){
if(err){
res.redirect("/campgrounds");
}
else{
res.redirect("/campgrounds/"+req.params.id);
}
})
});
This is the ejs one
<%-include ('../partials/header') %>
<div class="container">
<h1 style="text-align: center;"> Edit a <%= campground.name%></h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/campgrounds/<%=campground._id%>?_method=PUT" enctype="multipart/form-data" method="POST">
<div class="form-group">
<input class="form-control" type="text" name="name" value="<%= campground.name%>">
</div>
<div class="form-group">
<input class="form-control" type="number" name="price" value="<%= campground.price%> min="0.01" step="0.01"">
</div>
<div class="form-group">
<input class="form-control" type="file" name="image" value="\<%= campground.image%>">
</div>
<div class="form-group">
<input class="form-control" type="text" name="description" value="<%= campground.description %>">
</div>
<div class="form-group">
<button class="btn btn-primary btn-large btn-block">Submit</button>
</div>
</form>
Go back
</div>
</div>
<%-include ('../partials/footer') %>

How to fix Cannot PUT /blogs/:id

I am making RESTful BlogApp and PUT method is not working.I only get error saying Cannot PUT /blogs/:id. I don't see what could go wrong. Everything looks fine to me. Please let me know if you find a problem. I know this might be a bad post but it is one of my first posts. Here is what i coded:
<form action="/blogs/<%= blog._id %>?_method=PUT" method="POST" class="ui
form">
<div class="field">
<label for="blog[tittle]">Tittle</label>
<input name="blog[tittle]" type="text" value="<%=
blog.tittle %>">
</div>
<div class="field">
<label for="blog[image]">Image URL</label>
<input name="blog[image]" type="text" value="<%= blog.image
%>">
</div>
<div class="field">
<label for="blog[body]">Content</label>
<textarea name="blog[body]"><%= blog.body %></textarea>
</div>
<button type="submit" class="ui blue button">Save</button>
</form>
const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
const mongoosePassword = 'bm9kZS1yZXN0LWJsb2c=';
mongoose.connect('mongodb://mesopotamija9:' + mongoosePassword + '#node-
rest-blog-shard-00-00-xb2tn.mongodb.net:27017,node-rest-blog-shard-00-01-
xb2tn.mongodb.net:27017,node-rest-blog-shard-00-02-
xb2tn.mongodb.net:27017/test?ssl=true&replicaSet=node-rest-blog-shard-
0&authSource=admin&retryWrites=true', {useNewUrlParser: true});
app.set('view engine', 'ejs')
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.put('blogs/:id', function(req, res){
Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err,
updatedBlog){
if (err) {
res.redirect('/blogs');
console.log(err);
} else {
res.redirect('/blogs/' + req.params.id);
console.log(updatedBlog);
}
});
});

node.js express-uploadFile undefined

I'm trying to upload a .txt file with the middleware express-uploadFile. However, when I try to test it my file is undefined.
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var app = express()
app.use(fileUpload());
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/send', function(req, res){
console.log(req.files.UploadBox);
console.log(req.body.Question);
});
<form id="Izone" action="/send/" method="post" encType="multipart/form-data">
<input type="text" name="Question" id="Question" placeholder="Question" autofocus autocomplete="off"><br/><br/>
<label for="UploadBox" id="UploadBoxStyle"> Upload File </label>
<input type="file" name="UploadBox" id="UploadBox">
<input type="submit" name="send" id="send" value="send"/>
</form>
req.body.Question works fine. However, req.files gives me undefined.
I don't know if the issue is bodyParser or fileupload itselft.

Categories

Resources