How to receive uploaded file within object nodejs/multer

Viewed 516

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!'))
  }
}
1 Answers

While working through the problem with OP, it seems that all xhr had been merged into a function to simplify all the request. However, the data is transformed by JSON.stringify before sending, which is not what "multipart/form-data" should do.

"multipart/form-data" is used to handle blob, which normal HTTP couldn't really handle without some compromise (like encoding base64 or others, which result in even larger size). "multipart/form-data" is basically a stream upload, so there will be chunks that is loaded to ur server. Multer is used to handle this.

You can read more about the "multipart/form-data" here https://developer.mozilla.org/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data

Related