Error In Multer When Trying To Upload A Image - mysql

Currently new to multer, so here's my problem:
I kept getting the MulterError: Unexpected field as the output when i try to POST the jpg image into mysql. Can anyone see whats the bug in my code? Currently im trying to make a error message when an image of more than 1MB is uploaded.
var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + new Date().toISOString() + '-' + path.extname(file.originalname));
}
});
var upload = multer({storage: storage});
// Endpoint 13 (EXTRA FEATURE 1)
const fileFilter = (req, file, callback) => {
if(file.mimetype === 'image/jpg') {
callback(null,true);
}
callback(null,false);
}
var uploadFromDesktop = multer({
storage:storage,
limits: {
fieldSize: 1024 * 1024
},
fileFilter: fileFilter
});
app.post("/upload/", upload.single('productImage'), (req, res, next) => {
uploadFromDesktop(req,res),(error) => {
console.log(error);
if (error) {
if (error.code === 'LIMIT_FILE_SIZE') {
} else {
res.status(500).send({ 'status': status, 'error':error})
}
} else {
var temp = req.file.path;
var file = uploadDir + req.file.originalname;
var source = fs.createReadStream(temp);
var destination = fs.createWriteStream(file);
source.pipe(destination);
fs.unlink(temp);
source.on('end',function () {
var result = {
'status': 'success',
'file': file
}
fs.chmod(file,0777);
res.send(result);
})
source.on('error', function (error) {
var result = {
'status': 'Fail',
'error': error
};
res.send(result);
})
}
}
})

Try with fileSize:
limits: {
fileSize: 2 * 1024 * 1024 // 2 MB}

Related

Nodejs: Can't post a string filed and image on the same request with Express and Mysql

I am using mutler to upload image with post request and also string data.
When I upload only the image with Postman or React, it is working, but when I send also the strings, it shows this:
undefined
TypeError: Cannot read properties of undefined (reading 'filename')
The string got saved to MySQL but not the image.
That's my code for the Multer:
let storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/images/')
},
filename: (req, file, callBack) => {
const mimeExtension = {
'image/jpeg': '.jpeg',
'image/jpg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
}
callBack(null, file.originalname)
}
})
let upload = multer({
storage: storage,
fileFilter: (req, file, callBack) => {
// console.log(file.mimetype)
if (file.mimetype === 'image/jpeg' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/png' ||
file.mimetype === 'image/gif') {
callBack(null, true);
} else {
callBack(null, false);
req.fileError = 'File format is not valid';
}
}
});
And that's my post request:
router.post('/', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
console.log("You didnt upload a picture for your project");
}
const { title, about_the_project, project_link, user_id } = req.body
const projectnum = await SQL(`INSERT into project(title,about_the_project,project_link,user_id)
VALUES('${title}','${about_the_project}','${project_link}',${user_id}) `)
console.log(projectnum.insertId);
console.log(req.file && req.file.filename)
let imagesrc = 'http://127.0.0.1:5000/images/' + req.file && req.file.filename
await SQL(`UPDATE project SET image = '${imagesrc}' WHERE projectid = ${projectnum.insertId}`)
res.send({ msg: "You add a new project" })
} catch (err) {
console.log(err);
return res.sendStatus(500)
}
})
On React that's the code:
const PostNewProject = async () => {
let formData = new FormData()
formData.append('image', imgsrc)
const res = await fetch(`http://localhost:5000/project`, {
headers: { 'content-type': 'application/json' },
method: "post",
body: JSON.stringify({ title, about_the_project, project_link, languages, user_id }),formData,
// credentials: "include"
})
const data = await res.json()
if (data.err) {
document.getElementById("err").innerHTML = data.err
} else {
console.log(data);
document.getElementById("err").innerHTML = data.msg
}
}
And the input for the image upload
<Input
type='file'
name='image'
sx={{ width: '25ch' }}
onChange={(e) => setImgsrc(e.target.files[0])}
/>
Thank you for your help!
You did not write a comma after the filename and before the callback function in the Multer.
I think you should check you exports too.

TypeError: Cannot read properties of undefined (reading 'filename') in multer

I have a very similar problem with respect to this fellow community contributor. How do i produce multer error message in my postman I followed through the comments made by other users and it was successful! However, when i tried to post a image that is a jpg formatted image( which i managed to do before the editing), it now fails and state that TypeError: Cannot read property 'filename' of undefined.
// multer.js file
successfully setup multer
**please tell me why this error comes on my code and give me a solution**
const multer = require('multer');
const storage = multer.diskStorage({
fileSize: 1024*1024*2,
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
const filter = function (req, file, cb) {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(new Error('unsupported files'), false)
}
}
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter : filter
});
module.exports = upload;
//controller.js file
//create function
here's my logic to create a new user
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = { name: req.body.name, description: req.body.description, brand_url:
req.body.brand_url, image_file: req.body.file.filename }; getting error here
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}
//api.js file
//post API
router.post('/api/create', upload.single('image') ,controller.create) //when I am
sending file its throw back error undefined filename
Please make sure you have added enctype="multipart/form-data"
<form action="/api/create" enctype="multipart/form-data" method="post">
I have tested the codes & found the problem.
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = {
name: req.body.name,
description: req.body.description,
brand_url: req.body.brand_url,
image_file: req.file.filename
}; // Remove "body", I have tested, it works well.
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}

how to import excel file in to mysql using nodejs

I am trying to import data in excel file to mysql just like row colon using nodejs are there any references i can learn or any module in nodejs that does my work or any sample code
I used Npm packages "xlsx-to-json-lc" and "xls-to-json-lc" to import excel file to json directly without converting to csv. Hope this helps...
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = dateFormat(new Date(), "yyyy~mm~dd h~MM~ss");
cb(null, '`enter code here`templete' + '-' + datetimestamp + '.' +
`enter code here`file.originalname.split('.')[file.originalname.split('.').length - 1])
filename = file.fieldname;
}
});
var upload = multer({ //multer settings
storage: storage,
fileFilter: function (req, file, callback) { //file filter
if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length - 1]) === -1) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
}
}).single('file');
var exceltojson;
upload(req, res, function (err) {
if (err) {
res.json({ error_code: 1, err_desc: err });
return;
}
if (!req.file) {
//res.json({ error_code: 1, err_desc: err });
return;
}
if (req.file.originalname.split('.')[req.file.originalname.split('.').length - 1] === 'xlsx') {
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson({
input: req.file.path,
output: null, //since we don't need output.json
//lowerCaseHeaders: true
}, function (err, result) {
if (err) {
return res.json({ error_code: 1, err_desc: err, data: null });
}
else {
console.log(result);
}
});
})

How to upload file using multer and store details in database in mean rest app and retrieve it from angular.js

I am uploading file through my rest mean application, but i am not able to retrieve it back from backend . how do i retrieve it,
Here is upload code
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, mongoose.Types.ObjectId() + '-' + file.originalname);
}
});
var upload = multer({ storage : storage }).array('userPhoto',10);
upload(req,res,function(err) {
console.log(req.files);
var images =[];
for(var i=0; i<req.files.length; i++){
images[i]=req.files[i].path;
}
var newalbum = new albummodel({
image:images
});
newalbum.save(function(err, albm) {
if(err) {
res.json({success: false, msg: 'can't store.'});
} else {
console.log(albm);
}
});
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
Here is my retrieve code
albummodel.findOne({_id:req.params.id},function(err, docs){
res.json(docs);
})
This whole discussion help you. Please refer it.
https://github.com/Automattic/mongoose/issues/3079

Data not getting saved in the MongoDB from node.js

I want to create the rest api using node.js and mongodb
I am entering all the details and trying it to store it in the mongodb database.
// call the packages we need
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
// configure app
app.use(morgan('dev')); // log requests to the console
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
var mongoose = require('mongoose');
// mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o'); // connect to our database
mongoose.connect('mongodb://localhost:27017');
var Bear = require('./app/models/bear');
// create our router
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
bear.email= req.body.email; // set the bears email(comes from the request)
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
// get all the bears (accessed at GET http://localhost:8080/api/bears)
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')
// get the bear with that id
.get(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
res.json(bear);
});
})
// update the bear with this id
.put(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
bear.name = req.body.name;
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear updated!' });
});
});
})
// delete the bear with this id
.delete(function(req, res) {
Bear.remove({
_id: req.params.bear_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
// REGISTER OUR ROUTES -------------------------------
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
The Model is given below:-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String,
email: String
});
module.exports = mongoose.model('Bear', BearSchema);
I am trying it to save the name and the email in the mongodb database but only _id is created instead of name, email.
Here is the result:-
[
{
"_id": "567f1f92db24304013000001",
"__v": 0
},
{
"_id": "567f2765db24304013000002",
"__v": 0
}
]
Can anybody tell me why the data are not getting saved in the database.
Please kindly help.
Thanks in Advance.
I think your POST request is not good, so I made this simple script to check it out:
var XHR = (function() {
var _xhr = (function() {
try {
return new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
} catch (e) {}
})();
return function(method, url, params, callback) {
_xhr.onreadystatechange = function() {
if (_xhr.readyState == 4) {
var _response;
try {
_response = JSON.parse(_xhr.response);
} catch (e) {
_response = _xhr.responseText;
}
if (_xhr.status != 200) {
// catch an error
console.error('error', response);
} else {
if (callback) {
callback(_response);
} else {
// deal with it
}
}
}
}
if (!params) {
params = JSON.stringify({});
} else {
params = JSON.stringify(params);
}
_xhr.open(method, url, true);
// just json in this case
_xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
_xhr.send(params);
};
})();
fire it up in browser's console, like this
XHR('POST','api/bears', { name:'yogi', email:'yogi#bears.com'}, function(){ console.log(arguments) });
and your record will be saved.
{ "_id" : ObjectId("567e875d068748ee5effb6e0"), "email" : "yogi#bears.com" "name" : "yogi", "__v" : 0 }
Long story short - your code is okay, your POST is not.