i have a change user profile avatar page .. im using XHR to upload the picture .. then recieving it with multer (backend). the problem im facing is that the received data is empty , because im sending the picture inside and object
var loadFile = function(event) {
//avatar file
let file = event.target.files[0];
let formData = new FormData();
formData.append('userAvatarFile', file);
customAjax({
method: 'post',
route: '/profileEdit/userAvatar',
type: "multipart/form-data",
data: {
target: formData //the avatar file is inside this "data" object
})
};
The problem : as you can see im putting the 'formData' inside an object , but when i do that multer will not find the file , and have to send the formData like that .. How can i make multer read the file from inside the 'data' object ?
Backend Part:
//SET DESTINATION AND FILE NAME FOR THE UPLOADED IMAGES
const storage = multer.diskStorage({destination: __dirname +
'/../views/resources/images/avatar',
filename: function(req, file, cb){
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}});
//init upload for multer
const upload = multer({storage: storage,
limits: {
fileSize: 1000000
},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).single('userAvatarFile');
//SECURITY PART OF FILE UPLOADING
//check the uploaded files
function checkFileType(file, cb){
//Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
//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{
return cb(new Error('Images Only!'))
}
}