I am trying to use multer module in my website but my doubt is that we are declaring upload as constant const upload =multer({}); but then in the post method, we are using upload (req,res,error) method is it the same object or a different one. Can someone please help me out it would be a great help.
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).single('myImage');`
`app.post('/upload', (req, res) => {
upload(req, res, (err) => {
if(err){
res.render('index', {
msg: err
});
} else {
if(req.file == undefined){
res.render('index', {
msg: 'Error: No File Selected!'
});
} else {
res.render('index', {
msg: 'File Uploaded!',
file: `uploads/${req.file.filename}`
});
}
}
});
});
The upload is defined as object but in the post method we are defining a method
Related
I have this router and I'm using multer to store files. I need to varify is 'Key' Exists in the server. Only after that server will store the file.
router.post('/', (req, res) => {
console.log(req.body.key); // empty here
upload(req, res, async (err) => {
if (err) {
console.log(err);
res.send({ error: err.message });
} else {
console.log(req.body.key); //shows the key
store(req.file.filename, {filename: req.file.filename, downloaded: 0, key: req.body.key});
res.send({ success: true, downlink: req.file.filename});
}
});
});
let storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => {
const filename = `${uuid()}-${file.originalname}`;
cb(null, filename);
}
});
let upload = multer({
storage: storage,
limits: { fileSize: 15000000 },
}).single('file'); //name field name
How can I add a checkpoint to prevent Unauthorized file upload?
https://i.stack.imgur.com/gZAHE.png
I am using multer to save an image from the client to mongoDB, and then rendering that image to the client as per the requirement.
When attempting to save the image from the frontend, it is getting saved as a .txt document.
How do I save it as a .png? (I am using Express on Node)
var multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'src/');
},
filename: function(req, file, cb) {
cb(null, new Date().toISOString().replace(/:/g, '-')+ file.originalname);
}
});
var upload = multer({ storage: storage });
app.post('/test', upload.single('image'), (req, res, next) => {
var obj = {
name: req.body.name,
desc: req.body.desc,
img: {
data: fs.readFileSync(path.join(__dirname + '/src/' + req.file.filename)),
contentType: 'image/png'
}
}
Image.create(obj, (err, item) => {
if (err) {
console.log(err);
}
else {
item.save();
res.redirect('/admin');
}
});
});
Frontend
<img src="data:image/<%=image.img.contentType%>;base64,
<%=image.img.data.toString('base64')%>">
Upon clicking "Save as"
download.txt
My post method is a part of an API that I am using to upload files and to store them in a folder in a local directory. When the user uploads the file it gets stored in the local directory and the path of the image is logged in the console. I am trying to render the path that is logged in the POST method to the EJS template that I am rendering in the get route. I am new to express and node is there any way I can do this? Here is my code:
const storage = multer.diskStorage({
destination: './upload/images',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storage: storage,
limits:{
fileSize: 10485760
}
})
app.post("/upload", upload.single('profile'), (req, res) => {
res.redirect("/main")
let imgPath = req.file.path;
console.log(imgPath);
})
function errHandler(err, req, res, next) {
if (err instanceof multer.MulterError) {
res.json({
success: 0,
message: err.message
})
}
}
app.use(errHandler);
This logs "upload\images\profile_1609158104360.jpg"
My get function in which I am trying to access the loged path from the /upload post route
app.get("/main", function (req, res) {
if (req.isAuthenticated()) {
// res.render("main");
User.find({ "secret": {$ne: null}}, function(err, foundUser, imgPath){
if(err){
console.log(err);
}else{
if(foundUser){
res.render("main", {
usersWithSecrets: foundUser,
usersWithImage: imgPath
});
console.log(imgPath);
}
}
}
);
} else {
res.redirect("/login");
}
});
You cant. On post /upload you return redirect. Than browser makes get /main, which is totally different request.
So I am having an issue with multer that i can't figure out. When I add an item with an image everything works with no issues but if I try to add an item with no image it fails. I have an if statement that will define a default image if req.file is undefined but it fails with the error saying req.file.filename is undefined ... Here is the code
Multer setup:
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./public/uploads");
},
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var upload = multer({ storage: storage }).single("file");
route:
router.post("/item/add", middleware.isLoggedIn, (req, res) => {
User.findById(req.user._id, (err, user) => {
upload(req, res, err => {
if (err) {
req.flash("error", "failed to upload file");
return res.redirect("/products");
}
var item = new Item();
item.name = req.body.name;
item.description = req.body.description;
item.price = req.body.price;
item.createdBy = { id: req.user._id, username: req.user.username };
if (typeof req.file === undefined) {
item.image = "/uploads/no-img.png";
} else {
item.image = "/uploads/" + req.file.filename;
}
item.save(function(err) {
if (err) {
res.send(err);
}
return res.redirect("/products");
});
});
});
});
So I guess my question is... How would I set this up where it wont fail with no image selected?
Your problem is here:
if (typeof req.file === undefined) {
typeof returns a string.
Your check should be if (typeof req.file === "undefined") {
I want to upload image through multer but first i want to create a directory or folder for every user and then upload the image to that users folder.
If I create a folder for a user myself and upload, passing the user_id, the image is uploaded into that folder.
But if I do it through code, I am not able to do that.
When in destination I am adding req.body.user_id it gives me undefined.
like this :-
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/images/'+ req.body.user_id)
}
[
app.post('/test', function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/images/' )
},
filename: function (req, file, cb) {
cb(null, file.originalname + '-' + Date.now())
//console.log(file);
}
});
var upload = multer({ storage: storage }).single('image');
var formatted = new Date().toLocaleString();
upload(req, res, function (err) {
var data = {
"user_id": req.body.user_id,
"item_id": req.body.item_id,
"sell_type": req.body.sell_type,
"sell_name": req.body.sell_name,
"sell_location": req.body.sell_location,
"sell_price": req.body.sell_price,
"data_post": formatted
};
console.log("error ==>",err);
if(err){
res.status(400).json({
"status_code": 'ERROR',
"message": "image uploadinf Fail"
});
}else{
fs.exists("/var/www/html/Anoop/nodetest/images/" + data.user_id, (exists) => {
console.log(exists);
if(exists) {
res.status(200).json({
"status_code": "SUCCESS",
"message": "uploaded",
"data": req.file.path
});
}
else
{
mkdirp("/var/www/html/Anoop/nodetest/images/" + data.user_id, function (err, result) {
if (err) {
res.status(400).json({
"status_code": "ERROR",
"message": "dir not created"
});
} else {
//console.log(result);
res.status(200).json({
"status_code": "SUCCESS",
"message": "dir created",
"data": req.file.path
});
}
});
}
});
}
});
});
]
Try this code
const fs = require('fs')
const filesDir = 'files';
// check if directory exists
if (!fs.existsSync(filesDir)) {
// if not create directory
fs.mkdirSync(filesDir);
}