I'm using multer to upload a file. It's uploading fine but I can't work out how to get the generated filename it's made. I'd like to post it back into the response. The filename that's been made is highlighted in the comments:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../app/src/assets/game/src/assets/images/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.png') <!-- I need this in my postback response -->
}
});
const upload = multer({ storage: storage }).single('avatar');
router.post('/upload/', function (req, res) {
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
throw err;
}
res.json({
sucess: true,
message: 'Image was uploaded successfully'
});
// Everything went fine
})
});
For getting the image name for single image upload use req.file.filename :
res.json({
success: true,
message: 'Image was uploaded successfully',
filename: req.file.filename
});
For getting the images name for multiple images upload use req.files :
let filenames = []
for(let i = 0; i < req.files.length; i++) {
filenames.push(req.files[i].filename);
}
res.json({
success: true,
message: 'Image was uploaded successfully',
filename: filenames
});
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
route file
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
},
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5,
},
fileFilter: fileFilter,
});
router.post('/hiring', upload.single('resume'), (req, res, next) => {
console.log(req.file);
const hiring = new Hiring({
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
email: req.body.gender,
mobile: req.body.mobile,
resume: req.file.path,
});
hiring
.save()
.then((result) => {
console.log(result);
res.status(200).json({
message: 'Created user successfully',
createdUser: {
_id: result._id,
username: result.username,
email: result.email,
mobile: result.mobile,
resume: result.resume,
},
});
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
});
I am trying to post data in database through postman but it is getting error 'path undefined'. I tried to change folder path like './uploads/', '/uploads', 'uploads/' and 'uploads' but the problem is not solving.
error
TypeError: Cannot read properties of undefined (reading 'path')
please give the solution for this problem.
It appears req.file is undefined. which itself meant you are not uploading file via postman.
You have to attach file in postman with 'resume' as keyword after selecting mutlipart in body section.
check this screenshot
With dothttp
It would look like this
POST 'http://localhost:3000/hiring'
multipart(
'resume'< '<replace path to the resume here>',
)
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.
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);
}