My code below
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const path = require("path");
const bodyParser = require("body-parser");
Below is the config for the multer.
const multer = require("multer");
const upload = multer({ dest: 'uploads/'});
Edit:1.
Also tried this configuration instead of the direct upload variable.But this doesnt work either.
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads/");
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
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
});
Product add form processing.
Here i am processing the form and console.log always returns undefined.
router.post("/productadd", upload.single("image"), (req, res) => {
console.log(req.file);
const newProduct = {
imagePath: "https://source.unsplash.com/random/480*480",
title: req.body.title,
description: req.body.description,
price: req.body.price
};
new Products(newProduct).save().then(product => {
res.redirect("/products");
});
});
Here is my form for the file upload
<form action="/productadd" Method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" placeholder="Enter the Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="" cols="30" rows="10" class="form-control" placeholder="Enter the content"></textarea>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control" name="price" placeholder="Enter the Price">
</div>
<div class="form-group">
<label for="image">Choose an Image:</label>
<input type="file" class="form-control" name="image" />
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>
Related
const express = require("express");
const handlebars = require("express-handlebars");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine(".hbs", handlebars({ defaultLayout: "main", extname: ".hbs" }));
app.set("view engine", ".hbs");
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
mongoose.Promise = global.Promise;
mongoose.connect(
"mongodb://usresa:passcode#mongodb-rukshi-shard-00-00.nerbj.gcp.mongodb.net:27017,mongodb-rukshi-shard-00-01.nerbj.gcp.mongodb.net:27017,mongodb-rukshi-shard-00-02.nerbj.gcp.mongodb.net:27017/db_name?ssl=true&replicaSet=atlas-dxrzem-shard-0&authSource=admin&retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true }
);
const nameSchema = new mongoose.Schema({
name: String,
naquantityme: String,
description: String,
});
const User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.render("login", { layout: "loginlayout" });
});
app.get("/home", (req, res) => {
res.render("dashboard", { layout: "main" });
});
app.use("/AddProduct", (req, res) => {
res.render("AddProduct", { layout: "main" });
});
app.post("/addproductform", (req, res) => {
var myData = new User(req.body);
myData
.save()
.then((item) => {
res.send("Product saved to database");
})
.catch((err) => {`enter code here`
res.status(400).send("Unable to save to database");
});`enter code here
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
///// Front End
<form id="form_validation" method="post" action="/addproductform">
<div class="form-group form-float">
<input type="text" class="form-control" placeholder="Product Name" name="name"
required>
</div>
<div class="form-group form-float">
<input type="text" class="form-control" placeholder="Quantity" name="quantity"
required>
</div>
{{!-- <div class="form-group">
<div class="radio inlineblock m-r-20">
<input type="radio" name="gender" id="male" class="with-gap" value="option1">
<label for="male">Male</label>
</div>
<div class="radio inlineblock">
<input type="radio" name="gender" id="Female" class="with-gap" value="option2"
checked="">
<label for="Female">Female</label>
</div>
</div> --}}
<div class="form-group form-float">
<textarea name="description" cols="30" rows="5" placeholder="Description"
class="form-control no-resize" required></textarea>
</div>
{{!-- <div class="form-group">
<div class="checkbox">
<input id="checkbox" type="checkbox">
<label for="checkbox">I have read and accept the terms</label>
</div>
</div> --}}
<button class="btn btn-raised btn-primary waves-effect" id="submitDetails"
name="submitDetails" type="submit">SUBMIT</button>
</form>
This is appjs code. Rest I have AddProduct in views folder.
The default setting for accesing the view is from views folder.
This addproduct form is not submitting the datat to database.
How do we change the route of different views
This addproduct form is not submitting the datat to database.
This addproduct form is not submitting the datat to database.
This addproduct form is not submitting the datat to database.
I am getting an error in my application when I want to upload an image with Multer. I already tried to change the name and the loading address but still did not achieve anything. Any ideas ?
This is the code:
const multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb){
cb(null, path.join(__dirname,'../views/upload'));
},
filename: function(req, file, cb){
cb(null, file.fieldname + Date.now());
}
})
var upload = multer({
storage: storage
})
Route:
router.post('/user/change/image', upload.single('image'), isAuthenticated, (req, res) =>{
const file = req.file.image
if(!file) {
req.flash('error', 'Porfavor introduce un archivo valido')
} else {
res.send(file)
res.redirect('/user')
}
})
Form EJS:
<div class="tarjetaedit col-sm-6">
<form method="POST" action="/user/change/image" role="form" enctype="multipart/form-data">
<div class="form-group">
<legend class="legend">Imágen de perfil</legend>
<input type="file" class="form-control" name="image" accept="image/*">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-block">Subir foto</button>
</div>
</form>
</div>
Thanks to all ! I really need to fix this <3
I am uploading a file using multer but the problem is as I am trying to check if it's being uploaded or not using if (req.body.file) the app will not crash but the browser will say that the page is not available. Is there another way of checking if the file will be uploaded?
var multer = require('multer');
var storage = multer.diskStorage({
//multers disk storage settings
destination: function (req, file, cb) {
cb(null, 'public/uploads/')
},
filename: function (req, file, cb) {
//var datetimestamp = Date.now();
cb(null, file.originalname)
}
});
var upload = multer({
storage: storage
})
router.post('/adduser', upload.single('image'), function (req, res) {
console.log(req.body.name);
var data = {
name: req.body.name,
password: req.body.password,
image: 'uploads/' + req.file.originalname
}
users.insert(data, function (err, data) {
console.log(data);
res.redirect('/home');
});
});
<form action="/adduser" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="password" name="password" />
<input type="file" name="image" />
<input type="submit">
</form>
I am trying to upload a file to disk using multer. Here is my code:
const multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + '/uploads/')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
}
});
var upload = multer({storage: storage});
And here goes my form to collect the file and some extra input fields
<form method="post" enctype="multipart/form-data" action="/uploadfile">
<input name="cate" type="hidden" value="<%= category %>" id="cate" name="cate"></input>
<br>
<input type="file" name="uploadfile" class="btn-success" value="Select Source">
<input type="submit" class="btn-success" ><i class="fas fa-plus"></i> Add a new Source</input>
This function uploads public/img/bg.jpg to my database, thou i would like the file to be picked by the user. How can i get the filepath string in req.files object
fs.createReadStream('public/img/bg.jpg')
.pipe(fileUpload.createWriteStream())
.on('error', function(err) {
console.log("fail");})
.on('finish', function() {
console.log("success");
});
});
I have a simple blog app with Express.js in the back-end and React.js in the front-end. I am trying to add a feature to add pictures to the postgres database and my schema looks like this.
CREATE TABLE IF NOT EXISTS learningtable (
id BIGSERIAL PRIMARY KEY,
topstuff VARCHAR(255),
bottomstuff VARCHAR(255),
pic1 bytea
);
My upload form looks like this.
<form onSubmit={this.handleSubmit} >
<input type="text" name="topstuff" placeholder="top" onChange={this.handleTopChange} value={this.state.inputTopValue} /> <br/>
<input type="text" name="bottomstuff" placeholder="bottomt" onChange={this.handleBottomChange} value={this.state.inputBottomValue} /><br/>
<input type="file" name="pic1" /><br/>
<input type="submit" value="yeah boy" />
</form>
My router file looks like this
const express = require('express');
const myrouter = express.Router();
const controller = require('../controllers/learningController');
const 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())
}
})
var upload = multer({ storage: storage })
myrouter.post('/', upload.single('pic1'), controller.create);
module.exports = myrouter;
My controller is
const controller = {};
controller.create = (req, res) => {
console.log(req.body);
console.log(req.file)
LearningObject.create({
topstuff: req.body.topstuff,
bottomstuff: req.body.bottomstuff,
pic1: req.file,
})
.then(jsonAfterAdding => {
res.json({
message: 'okay',
jsonAfterAdding: jsonAfterAdding
});
}).catch(err => {
console.log(err);
res.status(400).json(err);
});
};
module.exports = controller;
And my model looks like this
const db = require('../db/config');
const LearningObject = {};
LearningObject.create = (blahblah) => {
return db.one (
`INSERT INTO learningtable
(topstuff, bottomstuff, pic1)
VALUES ($1, $2, $3) RETURNING *
`,
[blahblah.topstuff, blahblah.bottomstuff, blahblah.pic1]
);
};
module.exports = LearningObject;
When I console log req.file after trying to upload it says its undefined. The texts, "topstuff" and "bottomstuff" get saved to the database but I do not see the picture in the folder or the database.
try changing this in html file
<form onSubmit={this.handleSubmit} action='/' method="POST" enctype="multipart/form-data" >
<input type="text" name="topstuff" placeholder="top" onChange={this.handleTopChange} value={this.state.inputTopValue} /> <br/>
<input type="text" name="bottomstuff" placeholder="bottomt" onChange={this.handleBottomChange} value={this.state.inputBottomValue} /><br/>
<input type="file" name="pic1" /><br/>
<input type="submit" value="yeah boy" />
</form>