req.file == undefined, always undefined - node.js

I want to upload the excel file on the MySQL database and then import it back,
I have uses the technologies :
express
multer
mysql2
read-excel-file
sequelize
But when I upload the excel, req.file is showing undefined. in the excel controller folder.
I have checked the multer twice but it seems to be right.
I don't know what is the problem ...
Your answer will help me.
Thanks
Server-side code:
const multer = require("multer");
const excelFilter = (req, file, cb) => {
if (
file.mimetype.includes("excel") ||
file.mimetype.includes("spreadsheetml")
) {
cb(null, true);
} else {
cb("Please upload only excel file.", false);
}
console.log("done");
};
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/uploads");
},
filename: (req, file, cb) => {
console.log(file.originalname);
cb(null, `${Date.now()}-bestfile-${file.originalname}`);
},
});
var uploadFile = multer({ storage: storage, fileFilter: excelFilter });
module.exports = uploadFile;
Excel controller
const db = require("../../models");
const Branch = db.bestdata;
const readXlsxFile = require("read-excel-file/node");
const upload = async (req, res) => {
try {
console.log(req);
if (req.file == undefined) {
return res.status(400).send({ msg: "No, Excel File Uploaded" });
}
let path = __basedir + "/uploads/" + req.file.filename;
readXlsxFile(path).then((rows) => {
// skip header
rows.shift();
let branchArray = [];
rows.forEach((row) => {
let branchtoArray = {
id: row[0],
branch_name: row[1],
mgr_id: row[2],
mgr_start_date: row[3],
};
branchArray.push(branchtoArray);
});
Branch.bulkCreate(branchArray)
.then(() => {
res.status(200).send({
message: "Uploaded the file successfully: " + req.file.originalname,
});
})
.catch((error) => {
res.status(500).send({
message: "Fail to import data into database!",
error: error.message,
});
});
});
} catch (error) {
console.log(error);
res.status(500).send({
message: "Could not upload the file: " + req.file.originalname,
});
}
};
const GetImport = (req, res) => {
Branch.findAll()
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials.",
});
});
};
module.exports = {
upload,
GetImport,
};
Router:
const express = require("express");
const router = express.Router();
const excelController = require("../controller/BestData/excel.controller.js");
const uploadFile = require("../middlewares/upload.js");
let routes = (app) => {
router.post("/upload", uploadFile.single("file"), excelController.upload);
router.get("/import", excelController.GetImport);
app.use("/excel", router);
};
module.exports = routes;
Snapshot of postman test
enter image description here
Excel File uploading
enter image description here

The answer is simple: Destination and path should be the same.:

Related

Saving Images React To Nodejs

I am trying to upload an image from my front end to the backend but it it doesn't send the image in the request
It says that the formdata is empty and it says that there's no image found, where is the problem and how can I fix this error?
Here is the code from the Frontend made in react:
const [userInfo, setuserInfo] = useState({
file:[],
filepreview:null,
});
const handleInputChange = (event) => {
setuserInfo({
...userInfo,
file:event.target.files[0],
filepreview:URL.createObjectURL(event.target.files[0]),
});
}
const [isSucces, setSuccess] = useState(null);
const submit = async () =>{
const formdata = new FormData();
formdata.append('avatar', userInfo.file);
console.log(formdata)
Axios.post("http://localhost:4000/imageupload", formdata,{
headers: { "Content-Type": "multipart/form-data" }
})
.then(res => { // then print response status
console.warn(res);
if(res.data.success === 1){
setSuccess("Image upload successfully");
}
})
}
The code of the Backend made in NodeJS:
const storage = multer.diskStorage({
destination: path.join(__dirname, './temp', 'uploads'),
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
app.post('/imageupload', async (req, res) => {
try {
// 'avatar' is the name of our file input field in the HTML form
let upload = multer({ storage: storage}).single('avatar');
upload(req, res, function(err) {
// req.file contains information of uploaded file
// req.body contains information of text fields
if (!req.file) {
return res.send('Please select an image to upload');
}
else if (err instanceof multer.MulterError) {
return res.send(err);
}
else if (err) {
return res.send(err);
}
const classifiedsadd = {
image: req.file.filename
};
res.send("ok")
});
}catch (err) {console.log(err)}
})
Edit:
Multer is essentially a nodejs router,i.e. a function that can be pipelined between your HTTP request and HTTP response.
I think that you should first make multer analyze your HTTP content and to actually populate the req.file before actually evaluate express parsers do their job.
const storage = multer.diskStorage({
destination: path.join(__dirname, './temp', 'uploads'),
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
let upload = multer({ storage: storage});
app.post('/imageupload', upload.single('avatar'), async (req, res) => {
try {
// 'avatar' is the name of our file input field in the HTML form
// req.file contains information of uploaded file
// req.body contains information of text fields
if (!req.file) {
return res.send('Please select an image to upload');
}
else if (err instanceof multer.MulterError) {
return res.send(err);
}
else if (err) {
return res.send(err);
}
const classifiedsadd = {
image: req.file.filename
};
res.send("ok")
}catch (err) {console.log(err)}
})
I am assuming that your upload code is working. Have you tried to read the HTTP request from your browser to see that the image has been correctly attached to the request?
Because probably the issue lies in the fact that you are not actually parsing the image.
const file = new File(userInfo.file, "avatar.png", {
type: 'image/png' // choose the appropriate
});
const formdata = new FormData();
formdata.append('avatar', file);
console.log(formdata)

uploading files from react to node js with multer

I want to upload files from the form data in react which is being posted by axios like this.
const addNewProduct = () => {
const newProduct = {
name: name,
cost: cost,
size: size,
color: color,
material: material,
discount: discount,
description: description,
category: category
};
const nulls = Object.values(newProduct).filter(p => p === null);
if(nulls.length === 0 && images.imageFiles) {
let productFormData = new FormData();
productFormData.append('productInfo', JSON.stringify(newProduct));
productFormData.append('productImages', images.imageFiles);
const addUrl = "http://localhost:8080/cpnl/addproduct";
axios({
method: "POST",
url: addUrl,
data: productFormData,
headers: { "Content-Type": "multipart/form-data" }
})
.then((response) => {
console.log(response.data.msg);
})
.catch((response) => {
console.error(response);
});
}else {
Notiflix.Notify.Warning("Check your inputs!");
console.log(nulls);
console.log("product: \n" + JSON.stringify(newProduct));
}
};
then I want to upload images with multer to images folder. this is my code:
const storage = multer.diskStorage({
destination: "./public/images",
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).array("productImages", 5);
function checkFileType(file, cb) {
// Allowed ext
const filetypes = /jpeg|jpg|png/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Images Only!');
}
}
//receive form data from front-end and add new product to database
router.post('/addproduct', async (req, res) => {
upload(req, res, (err) => {
if(err) {
res.status(400).json({
msg: err
});
} else {
if(req.files == undefined) {
res.status(400).json({
msg: "Error: No file selected! please contact the developer."
});
} else {
data = req.body.productInfo;
res.status(200).json({
msg: "Files uploaded!"
});
console.log( "images: " + req.files);
console.log("data" + data);
}
}
});
});
first problem: I'm getting image files inside req.body.productImages and not inside req.files
second problem: when I send the request node js throws me this error:
TypeError: upload is not a function
why everything is messed up!?
Edit: I restarted the server and now I'm getting data but the files are not being uploaded. no error is shown.
UPDATE: second problem fixed
First Problem : You have used .array("productImages", 5); in your upload function. use .array("files", 5); to get the file in req.files.
Second Problem : I guess there is some typo error in your code upload(req, res, (err)... there is one extra bracket it should be only upload(req,res,err )...

multer req file is undefined but why?

Can anyone tell me why my req.file is undefined?
I add the content header type,
I add single.photo but I get no data
frontend:
## data is equal to this:
Object {
"filename": "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
"type": "image/jpg",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}
const uploadStory = async data => {
try {
const form = new FormData();
form.append('photo', data);
const options = {
headers: {
'Content-Type':'multipart/form-data',
'Accept':'application/json'
},
method: 'POST',
body: form
};
const res = await fetch('http://xxxxxxx.xx:3000/createstory', options);
const out = await res.json();
return out;
} catch(e) {
console.log(e);
return e;
}
};
export default uploadStory;
backend:
const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
console.log(req);
cb(null, `${file.filename}-${Date.now()}`)
}
});
const upload = multer({
storage: storage
}).single('photo');
module.exports = async (req, res, next) => {
upload(req, res, function(err) {
if(err) {
console.log(err)
return;
} else if (err instanceof multer.MulterError) {
console.log(err);
} else {
console.log(req.file);
console.log('hi')
}
});
};
..................................
..................................
..................................
..................................
Make sure your data object looks like this
{
name: "3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
type: "image/jpg",
uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-xxxxx-test/ImagePicker/3ccc61e1-3c49-4538-9594-b4987b3fa66f.jpg",
}
In your data Object your key is filename instead of name
Change your upload to this
const upload = multer({
storage: storage,
});
And then,
module.exports = upload.single('photo'), async (req, res) => {
try {
console.log(req.body); // Body Here
console.log(req.file); // File Here
res.status(500).send('Fetch Completed Successfully');
} catch (error) {
console.log(error);
res.status(500).send('Error');
}
}

How to create a filename from frontend?

I am creating a React and Node application, and at the moment I need to upload a PDF file, the code works well, but I was wondering how to use front variables to create the file name by multer.
The code...
Front:
const handleSubmit = async (e) => {
const dado = new FormData()
const year = data.split("/")
const dd = year[0];
const mm = year[1];
const aaaa = year[2];
dado.append('file', file)
dado.append('uni', uni)
dado.append('dd', dd)
dado.append('mm', mm)
dado.append('aaaa', aaaa)
console.log(dado)
axios.post("http://localhost:8080/api/comprebem/file", dado, {
})
.then(res => {
console.log(res.statusText)
})
}
Back:
const storage = multer.diskStorage({
destination:"../login/public/comprebem/ibama/",
filename: function (req, file, cb) {
console.log(file);
cb(null, `unidade${"req['uni']"}_data${file.originalname}` )
}
})
const upload = multer({ storage: storage }).single('file')
app.post('/api/comprebem/file',function(req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
} else if (err) {
return res.status(500).json(err)
}
return res.status(200).send(req.file)
})
});

Using Multer, how do I delete the previous image file from storage after a user uploaded another image?

I'm a newbie trying to learn Nodejs. I've been trying to resolve an issue using an NPM module called Multer. I can't seem to write the right code to delete a User's image file or overwrite if the user uploads another one. Sorry for the inconvenience. Please help
My Delete Route works perfectly deleting both the "Posts" and "Image". However, my edit Route gives the below error
{"Error":{"errno":-4058,"syscall":"unlink","code":"ENOENT","path":"C:\cms\public\uploads\image-1568050604308.png"}}
const publicUploads = path.join(__dirname, '../../../public/uploads/');
const storage =
multer.diskStorage({
destination: publicUploads,
filename(req, file, cb){
cb(null,`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
}
});
const upload = multer({
storage,
limits: {
fileSize: 1000000
},
fileFilter(req, file, cb){
if(!file.originalname.match(/\.(jpeg|jpg|png)$/)){
return cb(new Error('Please upload an image file'))
}
cb(null, true)
}
})
router.put('/admin/posts/edit/:id', upload.single('image'), async (req, res) => {
const updates = Object.keys(req.body);
const allowedUpdates = ['title', 'body', 'status', 'image', 'allowComments'];
const isValid = updates.every(update => allowedUpdates.includes(update));
if(!isValid){
return res.send({Error: 'Invalid Update'})
}
try {
const post = await Post.findOne({_id: req.params.id});
if(!post){
return res.send({Error: 'Could not find your post'})
}
if(req.file){
fs.unlinkSync(`${publicUploads}${post.image}`);
post.image = req.file.filename
}
updates.forEach(update => {
post[update] = req.body[update]
})
post.allowComments = req.body.allowComments === 'on'? true:false;
await post.save();
req.flash('notice', 'Your post was edited successfully!')
res.status(200).redirect('/admin/posts')
} catch (error) {
res.send({Error: error})
}
}, (error, req, res, next) => {
res.send({Error: error})
})
You can delete the image natively with the Node package "fs". You don't need to use Multer for this:
// Remove old photo
if (oldPhoto) {
const oldPath = path.join(__dirname, "..", "images", oldPhoto);
if (fs.existsSync(oldPath)) {
fs.unlink(oldPath, (err) => {
if (err) {
console.error(err);
return;
}
res.status(200).send(userObj);
});
}
}

Resources