How to have multiple file names while uploading with multer - node.js

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?

Related

How to upload image files in Postman and echo back the same image using Express and Multer

I am trying to upload a product using postman and anytime I submit; it sends back all the data with the image undefined as shown in this screenshot:
My controller file:
const gameRepository = require("../routes/repository")
exports.createGame = async (req, res, next) => {
try {
const PORT = 8000;
const hostname = req.hostname;
const url = req.protocol + '://' + hostname + ':' + PORT + req.path;
const payload = ({
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: url + '/imgs/' + req.path
});
let eachGame = await gameRepository.createGame({
...payload
});
console.log(req.body)
res.status(200).json({
status: true,
data: eachGame,
})
} catch (err) {
console.log(err)
res.status(500).json({
error: err,
status: false,
})
}
}
repository.js:
const Game = require("../models/gameModel");
exports.games = async () => {
const games = await Game.find();
return games;
}
exports.gameById = async id => {
const game = await Game.findById(id);
return game;
}
exports.createGame = async payload => {
const newGame = await Game.create(payload);
return newGame;
}
exports.removeGame = async id => {
const game = await Game.findById(id);
return game;
}
Multer.js:
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'imgs/jpg': 'jpg',
'imgs/jpeg': 'jpeg',
'imgs/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, path.join('../imgs'));
},
filename: (req, file, cb) => {
const name = file.originalname.split('').join(__);
const extension = MIME_TYPES[file.mimetype];
cb(null, name + new Date().toISOString() + '.' + extension);
}
});
module.exports = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 6
},
})
I am not sure about where I went wrong, that is why I need an external eye to help locate where the fault is coming from.
I have a feeling that I need to use body-parser or navigate into the image folder correctly, or multi-part form, I am not sure.
after many try and fail I finally figured it out.
turns out it has compatibility issues depending on your OS.
I use windows 10 and this resolved the issue for me
Here is my working code:
multer.js
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpeg',
'image/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, ('storage/imgs/'));
},
filename: (req, file, cb) => {
const extension = MIME_TYPES[file.mimetype];
// I added the colons in the date of my image with the hyphen
cb(null, `${new Date().toISOString().replace(/:/g,'-')}.${extension}`);
}
});
module.exports = multer({
storage: storage
})
In my controller.js
const gameRepository = require("../routes/repository");
exports.createGame = async (req, res, next) => {
try {
const payload = {
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: req.file.filename,
};
let eachGame = await gameRepository.createGame({
...payload,
});
res.status(200).json({
status: true,
data: eachGame,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
status: false,
});
}
};
exports.getGames = async (req, res) => {
try {
let games = await gameRepository.games();
res.status(200).json({
status: true,
data: games,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
status: false,
});
}
};
exports.getGameById = async (req, res) => {
try {
let id = req.params.id;
let gameDetails = await gameRepository.gameById(id);
req.req.status(200).json({
status: true,
data: gameDetails,
});
} catch (err) {
res.status(500).json({
status: false,
error: err,
});
}
};
exports.removeGame = async (req, res) => {
try {
let id = req.params.id;
let gameDetails = await gameRepository.removeGame(id);
res.status(200).json({
status: true,
data: gameDetails,
});
} catch (err) {
res.status(500).json({
status: false,
data: err,
});
}
};
:
Postman output
Thanks to this great community.

Send image from form-data and JSON data from postman for node js

Problem
How I received the image and JSON data from the postman in node js API? When I send the image from form-data and also send the JSON data only one received. If the image is shown in the request then JSON data not received and validation error occurred.
How I handle this case? Make separate API for image upload. What is the best way todo this
account.js
const express = require('express');
const multer = require('multer');
const { constants } = require('../helpers/contants');
const { commonValidation } = require('../validation/commonValidation');
const { validation } = require('../middleware/validation');
const crypto = require("crypto");
const {
updateProfile,
} = require('../controllers/account');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, `public/${constants.imageDir}`)
},
filename: async (req, file, callback) => {
var filetype = '';
if(file.mimetype === 'image/jpg') {
filetype = 'gif';
}
if(file.mimetype === 'image/png') {
filetype = 'png';
}
if(file.mimetype === 'image/jpeg') {
filetype = 'jpg';
}
callback(null, 'image-' + crypto.randomBytes(3).toString('hex') + '-' +
Date.now() + '.' + filetype);
}
})
var upload = multer({ storage: storage,fileFilter: (req, file, callback) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" ||
file.mimetype == "image/jpeg") {
callback(null, true);
} else {
callback(null, false);
return callback(new Error('Only .png, .jpg and .jpeg format allowed!'));
}
} });
const router = express.Router({ mergeParams: true });
router.use(upload.single('image'));
router.use((req, res, next) => {
if (!Array.isArray(req.image)) {
req.image = []
}
req.body = req.body.request
if (req.file) {
//set the avatar in req to get the image name in updateProfile controller
req.body.avatar = req.file.filename;
req.image.push(req.file.filename)
}
return next()
})
router
.patch('/', [commonValidation('updateProfile')], validation, updateProfile)
module.exports = router;
commonValidation
exports.commonValidation = (method) => {
switch (method) {
case 'updateProfile': {
return [
check('name', 'Name is required').not().isEmpty().trim().escape(),
]
}
}
validation
const { validationResult } = require('express-validator');
module.exports.validation = (req, res, next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
return next()
}
// err.message = 'ValidationError';
const extractedErrors = []
errors.array({ onlyFirstError: true }).map((err) => extractedErrors.push({
[err.param]: err.msg }))
next(extractedErrors);
}
account
exports.updateProfile = asyncHandler(async (req, res, next) => {
if(typeof req.body.avatar !== 'undefined'){
const oldImage = await User.findById(req.user._id);
//oldImage.avatar exist then delete the previous image from directory
if(oldImage.avatar){
deleteImageFromFolder('images',oldImage.avatar)
}
}
const user = await User.findByIdAndUpdate(req.user._id, req.body, {
new: true,
runValidators: true
});
const profile = user.getProfile();
res.status(200).json({
success: true,
data: profile
});
});
postman
In this below image JSON data and image received but the validation error occurs

Upload images from iOS is too slow

My React-Native iOS front-end can not upload images to my Node.JS (Express + Multer) back-end.
My front-end is React Native Android & iOS. The Android version works fine with no issues, however, uploading images from and iOS device doesn't work most of the time.
Once the upload request is sent, I can see the image file is added in FTP, however, very slowly, like a few KB every second. An image of 500 KB may take 3 minutes or more till the request times out. The file is added to the server partially and I can see change in size with each refresh.
Some [iOS] devices had no issues at all, uploads fast, however, the vast majority of devices are running into this issue.
No connectivity issues. The same host and network work perfectly with Android. Same with some iOS devices.
This is not limited to a specific iOS version or device. However, the devices who had the issue always have it, and those that don't, never have it.
How can I troubleshoot this?
POST request:
router.post('/image', (req, res) => {
console.log('image')
upload(req, res, (error) => {
if (error) {
console.log(error)
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'Invalid file type. Only JPG, PNG or GIF file are allowed.'
}));
} else {
if (req.file == undefined) {
console.log('un')
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'File size too large'
}));
} else {
var CaseID = req.body._case; // || new mongoose.Types.ObjectId(); //for testing
console.log(req.body._case + 'case')
var fullPath = "uploads/images/" + req.file.filename;
console.log(fullPath);
var document = {
_case: CaseID,
path: fullPath
}
var image = new Image(document);
image.save(function(error) {
if (error) {
console.log(error)
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'bad request error'
}));
}
return res.send(JSON.stringify({
data: image,
state: 200,
message: 'success'
}));
});
}
}
});
});
Upload.js:
const multer = require('multer');
const path = require('path');
//image upload module
const storageEngine = multer.diskStorage({
destination: appRoot + '/uploads/images/',
filename: function (req, file, fn) {
fn(null, new Date().getTime().toString() + '-' + file.fieldname + path.extname(file.originalname));
}
});
const upload = multer({
storage: storageEngine,
// limits: {
// fileSize: 1024 * 1024 * 15 // 15 MB
// },
fileFilter: function (req, file, callback) {
validateFile(file, callback);
}
}).single('image');
var validateFile = function (file, cb) {
// allowedFileTypes = /jpeg|jpg|png|gif/;
// const extension = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
// const mimeType = allowedFileTypes.test(file.mimetype);
// if (extension && mimeType) {
// return cb(null, true);
// } else {
// cb("Invalid file type. Only JPEG, PNG and GIF file are allowed.")
// }
var type = file.mimetype;
var typeArray = type.split("/");
if (typeArray[0] == "image") {
cb(null, true);
}else {
cb(null, false);
}
};
module.exports = upload;
React Native Upload function:
pickImageHandler = () => {
ImagePicker.showImagePicker(this.options1, res => {
if (res.didCancel) {
} else if (res.error) {
} else {
this.setState({upLoadImage:true})
var data = new FormData();
data.append('image', {
uri: res.uri,
name: 'my_photo.jpg',
type: 'image/jpg'
})
data.append('_case',this.state.caseID)
fetch(url+'/image'
, {method:'POST',
body:data
}
)
.then((response) => response.json())
.then((responseJson) =>
{
this.setState(prevState => {
return {
images: prevState.images.concat({
key: responseJson._id,
src: res.uri
})
}
}
)
this.setState({upLoadImage:false})
})
.catch((error) =>
{
alert(error);
});
}
}
)
}
Any suggestions?
Thanks
I saw your answer from UpWork
please try this way,
I'm using API Sauce for API calls
export const addPartRedux = (data) => {
return (dispatch, getState) => {
console.log('addPArtREdux', data);
const values = {
json_email: data.token.username,
json_password: data.token.password,
name: data.text ? data.text : '',
car: data.selected.ID,
model: data.selectedSub.ID,
make_year: data.selectedYear,
type: data.type,
ImportCountry: data.import_image ? data.import_image : '',
FormNumber: data.number ? data.number : '',
do: 'insert'
};
const val = new FormData();
Object.keys(values).map((key) =>
val.append(key, values[key])
);
if (data.imageok) {
val.append('image', {
uri: data.image.uri,
type: data.image.type,
name: data.image.name
});
}
dispatch(loading());
api
.setHeader('Content-Type', 'multipart/form-data;charset=UTF-8');
api
.post('/partRequest-edit-1.html?json=true&ajax_page=true&app=IOS',
val,
{
onUploadProgress: (e) => {
console.log(e);
const prog = e.loaded / e.total;
console.log(prog);
dispatch(progress(prog));
}
})
.then((r) => {
console.log('Response form addPartRedux', r.data);
if (r.ok === true) {
const setting = qs.parse(r.data);
dispatch(addpart(setting));
} else {
dispatch(resetLoading());
dispatch(partstError('Error Loading '));
}
})
.catch(
(e) => {
console.log('submitting form Error ', e);
dispatch(resetLoading());
dispatch(partstError('Try Agin'));
}
);
};
};

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));
}
});

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');}

Resources