Multer - Stop File Uploading If Form Validation Fails - node.js

i have mixed form with file upload and normal form fields, and while sending this form to Nodejs server i am validating form but problem is that i do not know how to stop uploading the file if (for example) one of the form field is empty.
so for example:
if(name.trim().length < 1){
//stop uploading of file
return res.status(409).send({
message: 'provide name'
})
}
how can i do that (Multer & ExpressJS)?

I was using following code in my case (node & express).
From routes.js file I am calling this insertRating method. like below
//routes.js
router.post('/common/insertrating',RatingService.insertRating);
//controller class
// storage & upload are configurations
var storage = multer.diskStorage({
destination: function (req, file, cb) {
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();
console.log("month and yeare are " + month + " year " + year);
var quarterMonth = "";
var quarterYear = "";
var dir_path = '../../uploads/' + year + '/' + quarterMonth;
mkdirp(dir_path, function (err) {
if (err) {
console.log("error is cominggg insidee");
}
else {
console.log("folder is createtd ")
}
cb(null, '../../uploads/' + year + '/' + quarterMonth)
})
console.log("incomingggg to destination");
},
filename: function (req, file, cb) {
console.log("incoming to filename")
cb(null, Date.now() + "_" + file.originalname);
},
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1048576 * 5
},
fileFilter: function (req, file, callback) {
var ext = path.extname(file.originalname);
ext = ext.toLowerCase();
console.log("ext isss " + ext);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg' && ext !== '.pdf' && ext !== '.txt'
&& ext !== '.doc' && ext !== '.docx' && ext !== '.xlsx' && ext !== '.xls'
) {
return callback(new Error('Only specific extensions are allowed'))
}
callback(null, true)
}
}).array('files', 5);
// calling below insertRating method from routes js file...
exports.insertRating = async function (req, res) {
let quarterData = req.query.quarterData;
quarterData = JSON.parse(quarterData);
if (quarterData != null) { // here you can check your custom condition like name.trim().length
req.files = []; // not required
upload(req, res, async function (err) { // calling upload
if (err) {
res.send("error is cominggg")
return;
} else {
res.send("file is uploaded");
}
//
});
}
else {
res.send("filed must not be empty");
}
}

You can simply throw error:
in express::
app.get("/upload-image", multterUpload.single("image"), (req, res, next)=>{
try{
if(name.trim().length < 1) {
throw new Error("name length is not valid");
//or
return res.status(409).json({msg: "failed"});
}
// you all operation ....
res.status(200).json({msg: "success"});
}cathc(e=>{
next(e)
});
})
this is something you can do or you can return something else instead of throwing an error.

Related

Cannot trim exceljs cell value

I want to get values from an Excel file :
var Excel = require("exceljs");
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../config/uploads/'));
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage });
router.post("/affecterConducteur", upload.single('fichier'), function(req, res) {
var filename = req.file.destination + req.file.filename;
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename).then(function() {
var sheet = workbook.getWorksheet(1);
for(var r=2; r<=sheet.rowCount; r++) {
var row = sheet.getRow(r);
var msisdn = row.getCell(1).value, immatriculation = row.getCell(2).value;
if (msisdn != null) {
msisdn = msisdn.trim();
msisdn = (msisdn.substr(0,3) == "034" ? msisdn : "0".concat(msisdn));
immatriculation = immatriculation.trim();
immatriculation = immatriculation.replace(/ /g, "");
var sql = "insert into "+db.getPrefixNomTables()+"conducteur(type_conducteur_id, msisdn) "+
"values((select type_conducteur_id from "+db.getPrefixNomTables()+"type_conducteur where lower(type_conducteur_lib) = 'cdz'), '"+msisdn+"')";
connexion.query(sql, function(err, rows) {
if (err)
throw err;
var maj = "update "+db.getPrefixNomTables()+"vehicule "+
"set conducteur_id = "+rows.insertId+" where replace(immatriculation, ' ', '') = '"+immatriculation+"'";
connexion.query(maj, function(err2, rows2) {
if (err2)
throw err2;
});
});
}
}
res.send("");
});
});
At runtime I get TypeError: msisdn.trim is not a function. So what is wrong ?
You may want to check that msisdn is a string instead of checking that it's not null.
if(typeof msisdn === 'string')
It's complaining that trim isn't a function because you are trying to perform it on something that isn't a string.

Upload photo into a folder in nodejs

I want to upload an image in a folder using nodejs but i don't know how to do it
Here is my insert in my ImageDao
exports.insert = function(data, callback){
console.log("in imagesDao insert");
var query = " insert into " + tableName + " (url,ajoute_par)";
query = query + " values(?,?);";
var values = [data.url , data.ajoute_par];
// var values = [encodeURIComponent(data.url) , data.ajoute_par];
database.execute(query, values, function(){
callback();
});
}
And here is my image controller
// insert
exports.write = function(request, response){
console.log("in images write");
// Get the data.
var postData = "";
request.on('data', function(data){ // request.on is a listener. Call when data can be read
postData = postData + data;
});
request.on('end', function(){ // Called when data has been read
var dataObj = JSON.parse(postData);
dao.insert(dataObj, function(){
send(response, '{"write result" : "Inserted successfuly"}');
});
});
}
To upload files you can use multer module of nodejs. https://github.com/expressjs/multer
images_storage: function () {
return multer.diskStorage({
destination: function (req, file, cb) {
mkdirp(Config.upload_images_path, function (err) {
});
cb(null, Config.upload_images_path)
}
,
filename: function (req, file, cb) {
var getFileExt = function (fileName) {
var fileExt = fileName.split(".");
if (fileExt.length === 1 || (fileExt[0] === "" && fileExt.length === 2)) {
return "";
}
return fileExt.pop();
}
cb(null, Date.now() + '.' + getFileExt(file.originalname))
}
});
},
// Image uploading
const fs = require('fs');
const multer = require('multer');
const Uploads = multer({
storage: utility.images_storage(),
fileFilter: function (req, file, cb) {
if (Config.image_format_arr.indexOf(file.mimetype))
cb(null, true);
else
cb(null, false);
}
});
//And in your route you can use the upload function
router.post('/upload-logo', Uploads.single('school_logo'), function (req, res, next) {
var school_id = req.body.school_id;
var result = {flag: false, message: "Error Occurred! in saving school logo."};
console.log("REQUEST FILES " + req.file);
// Save School Logo
if (typeof req.file != 'undefined' && req.file.size > 0) {
School.findByIdAndUpdate(school_id, {
$set: {
school_logo: req.file.filename
}
}, {'new': true}, function (err, school_details) {
console.log("school_details " + school_details);
if (!err && school_details) {
result.flag = true;
result.message = "School logo has been successfully updated";
result.path = '/uploads/images/' + school_details.school_logo;
//req.session.school_details = school_details;
utility.upgradeSchoolLogoSessionValue(school_details, false, function (updated_school_details) {
console.log("BEFOR SESSION IS UPDATED" + JSON.stringify(req.session.school_details));
req.session.school_details = updated_school_details;
console.log("SESSION IS UPDATED" + JSON.stringify(req.session.school_details));
});
console.log("FILE NAME IS THIS " + req.file.filename);
}
res.json(JSON.stringify(result));
});
}
else {
res.json(JSON.stringify(result));
}
});

How to have multiple file names while uploading with multer

My code is as shown below:
const multer = require('multer');
let upload = multer();
let profile_image = '';
const storage = multer.diskStorage({
destination(req, file, callback) {
callback(null, './public/images')
},
filename(req, file, callback) {
profile_image = `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`;
callback(null, profile_image);
}
});
const userData = (req, res) => {
upload = multer({
limits: {
fileSize: 1000000,
files: 2
},
storage,
fileFilter(req, file, callback) {
const ext = path.extname(file.originalname);
if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(res.end('Only images are allowed'), null)
}
callback(null, true);
}
}).any();
upload(req, res, err => {
const foodtruck_name = req.body.foodtruck_name;
const foodtruck_tag = req.body.foodtruck_tag;
console.log(`foodname${foodtruck_name}`);
console.log("error" + err);
console.log("profile image" + profile_image);
if ((!foodtruck_name) || (foodtruck_name.trim() == '')) {
console.log("fooddddname " + foodtruck_name);
res.json({
status: '404',
message: 'Please enter valid foodtruck name'
});
} else {
const truck = new foodTruck();
truck.foodtruck_name = foodtruck_name,
truck.foodtruck_tag = foodtruck_tag,
awsUpload.fileUpload(profile_image).then((result) => {
truck.foodtruck_img = "https://myWebsite.com/" +
profile_image;
awsUpload.fileUpload(profile_image).then((result) => {
truck.foodtruck_logo = "https://myWebsite.com/" +
profile_image;
truck.save((err, trucSaved) => {
res.json({
status: '200',
message: 'Thanks for registering with quflip',
data: trucSaved
});
});
}).catch((errMsg) => {
res.json({
status: '400',
message: errMsg
})
});
}).catch((errMsg) => {
res.json({
status: '400',
message: errMsg
})
});
}
});
};
Here, I am able to upload multiple images successfully , but I am not able to get the names for each individual file while uploading. how can I have them inside upload(req, res, err => { function?

Uploading multiple files with multer, but from different fields?

How can I have multer accept files from multiple file type fields?
I have the following code that uploads a single file, using multer in node.js:
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public/uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage });
app.post('/rest/upload', upload.array('video', 1), function(req, res, next){
...
}
From the following form, on the condition only the video field has a value (if I specify both I get an 'Unexpected field' error):
<form action="/rest/upload" method="post" enctype="multipart/form-data">
<label>Video file: </label> <input type="file" name="video"/>
<label>Subtitles file: </label> <input type="file" name="subtitles"/>
<input type="submit"/>
</form>
It is not clear from the documentation how to approach this? Any suggestions would be appreciated. BTW I have tried the following parameter variations, without success:
app.post('/rest/upload', [upload.array('video', 1), upload.array('subtitles', 1)] ...
app.post('/rest/upload', upload.array('video', 1), upload.array('subtitles', 1), ...
app.post('/rest/upload', upload.array(['video', 'subtitles'], 1), ...
What you want is upload.fields():
app.post('/rest/upload',
upload.fields([{
name: 'video', maxCount: 1
}, {
name: 'subtitles', maxCount: 1
}]), function(req, res, next){
// ...
}
Using Multer Upload Files From Two Fields of Separate Forms on Different Pages
In this example I have two fields - resume and image. Resume in one form and Image in other. Both are on separate pages.
First import dependencies
const path = require('path'); // for getting file extension
const multer = require('multer'); // for uploading files
const uuidv4 = require('uuidv4'); // for naming files with random characters
Define fileStorage and fileFilter:
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => { // setting destination of uploading files
if (file.fieldname === "resume") { // if uploading resume
cb(null, 'resumes');
} else { // else uploading image
cb(null, 'images');
}
},
filename: (req, file, cb) => { // naming file
cb(null, file.fieldname+"-"+uuidv4()+path.extname(file.originalname));
}
});
const fileFilter = (req, file, cb) => {
if (file.fieldname === "resume") { // if uploading resume
if (
file.mimetype === 'application/pdf' ||
file.mimetype === 'application/msword' ||
file.mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
) { // check file type to be pdf, doc, or docx
cb(null, true);
} else {
cb(null, false); // else fails
}
} else { // else uploading image
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) { // check file type to be png, jpeg, or jpg
cb(null, true);
} else {
cb(null, false); // else fails
}
}
};
Middleware for multer
app.use(
multer(
{
storage: fileStorage,
limits:
{
fileSize:'2mb'
},
fileFilter: fileFilter
}
).fields(
[
{
name: 'resume',
maxCount: 1
},
{
name: 'image',
maxCount: 1
}
]
)
);
And then call your routes. You may need to add csrf protection or authentication along with this for security. But this should work fine.
If you want to upload multiple files/images from the same form, I have used the below code and it works fine. The path of the image is stored in the database; I will skip the database path and go straight to the upload function and how the fields are passed to the save function.
const path = require('path');
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
if (file.fieldname === "profile") {
cb(null, './uploads/profiles/')
}
else if (file.fieldname === "natid") {
cb(null, './uploads/ids/');
}
else if (file.fieldname === "certificate") {
cb(null, './uploads/certificates/')
}
},
filename:(req,file,cb)=>{
if (file.fieldname === "profile") {
cb(null, file.fieldname+Date.now()+path.extname(file.originalname));
}
else if (file.fieldname === "natid") {
cb(null, file.fieldname+Date.now()+path.extname(file.originalname));
}
else if (file.fieldname === "certificate") {
cb(null, file.fieldname+Date.now()+path.extname(file.originalname));
}
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 10
},
fileFilter: (req, file, cb) => {
checkFileType(file, cb);
}
}).fields(
[
{
name:'profile',
maxCount:1
},
{
name: 'natid', maxCount:1
},
{
name: 'certificate', maxCount:1
}
]
);
function checkFileType(file, cb) {
if (file.fieldname === "certificate") {
if (
file.mimetype === 'application/pdf' ||
file.mimetype === 'application/msword' ||
file.mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
) { // check file type to be pdf, doc, or docx
cb(null, true);
} else {
cb(null, false); // else fails
}
}
else if (file.fieldname === "natid" || file.fieldname === "profile") {
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'||
fiel.mimetype==='image/gif'
) { // check file type to be png, jpeg, or jpg
cb(null, true);
} else {
cb(null, false); // else fails
}
}
}
//at the save function
upload(req, res, (err) => {
if (err) {
console.log(err);
} else {
if (req.file == "undefined") {
console.log("No image selected!")
} else {
let datecreated = new Date();
let fullnames = req.body.firstname + ' ' + req.body.lastname;
let formatedphone = '';
let phone = req.body.personalphone;
if (phone.charAt(0) == '0') {
formatedphone = '+254' + phone.substring(1);
} else if ((phone.charAt(0) == '+') && (phone.length > 12 || phone.length <= 15)) {
formatedphone = phone
}
let teachers = {
"teacherid": teacherid,
"schoolcode": req.body.schoolcode,
"fullnames": fullnames,
"email": req.body.email,
"dateofbirth": req.body.dateofbirth,
"nationalid": req.body.nationalid,
"personalphone": formatedphone,
"profile": req.files.profile[0].path,
"natid": req.files.natid[0].path,
"certificate":req.files.certificate[0].path
}
connection.query('INSERT INTO teachers SET ?', teachers, (error, results, fields) => {`enter code here`
if (error) {
res.json({
status: false,
message: 'there are some error with query'
})
console.log(error);
} else {console.log("Saved successfully");
}
this worked for Me. complete example
var multer = require('multer')
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/audio');
},
filename: function(req, file, callback) {
console.log(file);
if(file.originalname.length>6)
callback(null, file.fieldname + '-' + Date.now() + file.originalname.substr(file.originalname.length-6,file.originalname.length));
else
callback(null, file.fieldname + '-' + Date.now() + file.originalname);
}
});
const upload = multer({ storage: storage });
router.post('/save/audio',upload.fields([{
name: 'audio', maxCount: 1
}, {
name: 'graphic', maxCount: 1
}]) ,(req, res) => {
const audioFile = req.files.audio[0];
const audioGraphic = req.files.graphic[0];
const fileName = req.body.title;
saveAudio(fileName,audioFile.filename,audioGraphic.filename,req.body.artist,function (error,success) {
req.flash('success','File Uploaded Successfully')
res.redirect('/')
});
})
Did you try to use multer().any()?
I just need upload fields store in a arry
const express = require("express");
const category_route = express();
const bodyParser = require('body-parser');
category_route.use(bodyParser.json());
category_route.use(bodyParser.urlencoded({extended:true}));
const controller = require('../Controller/Category');
const Multer = require('multer')
const Path = require('path');
const multer = require("multer");
category_route.use(express.static('public'));
 const storage = multer.diskStorage({
    destination : function(req,files,cb){
        cb(null,Path.join(__dirname,'../public/category'),function(err,sucess){
            if(err){
                throw err;
            }
        });
    },
    filename:function(req,files,cb){
        const name = Date.now()+'-'+ files.originalname;
        cb(null,name, function(err, sucess){
            if(err){
                throw err;
            }
        });
    } 
 });
 const upload = multer({storage:storage})
category_route.post('/add-category',upload.fields([
    {
      name: "icon",
      maxCount: 1,
    },
    {
      name: "banner",
      maxCount: 1,
    }
  ]), controller.addCategory);
module.exports = category_route;
/* controller code*/
const Category = require("../Model/Category");
const addCategory = async (req, res) => {
  try {
    var arrIcon = [];
    for(let i=0; i<req.files.length; i++){
      arrIcon[i] = req.files[i].filename;
    }
    var arrBanner = [];
    for(let j=0; j<req.files.length; j++){
      arrBanner[j] = req.files[j].filename;
    }
    const catData = await Category.find();
    
    if (catData.length > 0) {
      let checking = false;
      catData.every((i) => {
        if (i.name.toLowerCase() === req.body.name.toLowerCase()) {
          checking = true;
          console.log("FOUND");
          return false;
        }
        console.log("NOT-FOUND");
        return true;
      });
      if (checking === false) {
        const data = new Category({
          name: req.body.name,
          camission: req.body.camission,
          icon: arrIcon,
          banner: arrBanner,
          mtitel: req.body.mtitel,
          mdiscp: req.body.mdiscp,
        });
        const result = await data.save();
        res.send(result);
      } else {
        res.send("Category is Already exieet");
      }
    } else {
      const data = new Category({
        name: req.body.name,
        camission: req.body.camission,
        icon: arrIcon,
        banner: arrBanner,
        mtitel: req.body.mtitel,
        mdiscp: req.body.mdiscp,
      });
      const result = await data.save();
      res.send(result);
    }
  } catch (error) {
    console.log(error);
    res.send("somthing Wrong");
  }
};
module.exports = { addCategory };
upload(req, res, (err) => {
if (err) {
console.log(err);
} else {
if (req.file == "undefined") {
console.log("No image selected!")
} else {
let datecreated = new Date();
let fullnames = req.body.firstname + ' ' + req.body.lastname;
let formatedphone = '';
let phone = req.body.personalphone;
if (phone.charAt(0) == '0') {
formatedphone = '+254' + phone.substring(1);
} else if ((phone.charAt(0) == '+') && (phone.length > 12 || phone.length <= 15)) {
formatedphone = phone
}
let teachers = {
"teacherid": teacherid,
"schoolcode": req.body.schoolcode,
"fullnames": fullnames,
"email": req.body.email,
"dateofbirth": req.body.dateofbirth,
"nationalid": req.body.nationalid,
"personalphone": formatedphone,
"profile": req.files.profile[0].path,
"natid": req.files.natid[0].path,
"certificate":req.files.certificate[0].path
}
connection.query('INSERT INTO teachers SET ?', teachers, (error, results, fields) => {
if (error) {
res.json({
status: false,
message: 'there are some error with query'
})
console.log(error);
} else {
console.log('Saved successfully');}

Redirect page after upload stopped using Nodejs and multer

I am quite new in Node.js and express framework.
I wanted to create a service to upload file where it will display the image if the file type is an image. If the file is not an image it suppose to display error message to the user. I am using multer to upload file and if the file extension doesnt match with any of the predefined extension, it will return false to stop the upload process. But somehow it doesnt redirect the page to the error page if the upload stopped. Does the return false stopped the entire POST process? Is there any way for me to display error message if the upload stopped?
module.exports=function(app)
{
var express=require('express');
var multer=require('multer');
var path=require('path');
var fs=require('fs');
var bodyParser=require('body-parser');
var done = false;
var targetPath="";
app.use(bodyParser.urlencoded({uploadDir: '/uploads',extended:true, keepExtensions:true}));
app.use(function(req,res,next)
{
var handler = multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
if(file.extension != 'png' && file.extension != 'jpg' && file.extension != 'jpeg' && file.extension != 'gif')
{
done = false;
return false;
}
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
targetPath = file.path;
done = true;
}
});
handler(req, res, next);
});
app.get('/',function (req,res)
{
res.render('newindex.jade')
});
app.get('/errorpage', function (req,res)
{
res.render('errorpage.jade')
})
app.post('/uploads', function (req,res)
{
if(done = true)
{
console.log(req.files);
//res.end("Image has been uploaded at " + targetPath);
res.redirect("/" + targetPath);
targetPath="";
//res.send('<img src="' + targetPath + '">');
}
else
{
res.redirect("./errorpage")
}
});
app.get('/uploads/:file', function (req, res)
{
file = req.params.file;
var img = fs.readFileSync("./" + "/uploads/" + file);
res.writeHead(200);
res.end(img, 'binary');
});
}
I think that you can add req, res in onFileUploadStart() and insert res.doSomething() before the line "return false;". For example:
onFileUploadStart: function (file, req, res) {
{
done = false;
res.json({message: "Upload failed"})
return false;
}
console.log(file.originalname + ' is starting ...')
}

Resources