Upload image to my nodejs api


#1

Hi guys, this is my first topic and i tried hard on this problem
I already make some function in my nodejs api for uploading images using multer and it works with postman
This is the code

route //api/user/upload/userphoto/:user_id
uploadController.userPhoto = async (req, res) => {    
      if(!req.params.user_id){
         res.json({status: 400, message: 'User id gak ada',});
      }else{
        var user_id = req.params.user_id
        var newNameUpload;
        var direktori = './public/uploads/userphoto/';
        var savedbdirektori = './public/uploads/userphoto/';
        //Destination storage
        var storage = multer.diskStorage({      
          destination: direktori,
          filename: function (req, file, callback) {
            newNameUpload = file.fieldname + '-' + user_id + path.extname(file.originalname).toLowerCase();
            callback(null, newNameUpload);
          }
        });
        // multer buat function upload
        var upload = multer({ 
            storage : storage,
            fileFilter: function (req, file, callback) {
              var ext = path.extname(file.originalname).toLowerCase();
              if(ext !== '.png' && ext !== '.jpg' && ext !== '.jpeg') {
                  return callback(new Error('Only images are allowed'))
              }
              callback(null, true)
            },
            limits: {          
              fileSize: 5 * 1024 * 1024 //  file sized limits upload 5 MB
            } 
        }).single('UserPhoto');
      //upload function
          upload(req, res, function(err) {            
            if(err) {
              if (err.code == 'LIMIT_FILE_SIZE') {
                res.json({status: 400, message: 'File berukuran melebihi yang diizinkan.', err: err});
              } else {
                res.json({status: 500, message: 'File gagal diunggah.', err: err});
              }
            } else if (req.file == null || req.file == 0) {
              res.json({status: 400, message: 'File kosong, silahkan pilih file kembali'});
            } else {
              var direktoriPhoto = savedbdirektori + newNameUpload
              var queryUpdateUserPhoto = 'UPDATE user SET photo = ? WHERE user_id = ?';
              req.getConnection(function(err,connection){
                connection.query(queryUpdateUserPhoto,[direktoriPhoto,user_id],function(err,results){
                    if(err)
                      console.log("Error Selecting : %s ", err);
                    else if(results.length){
                      res.json({status: 404, message: 'User ID not Found' });
                    }
                    else{
                      res.json({status: 200 , message: 'Success Update Photo User',picture : direktoriPhoto});   
                    }
                });
              });
            }
          });
      }
}

And now i tried to take upload my photo from ionic mobile apps. i already did code this but the problem is my photo file undefined and didnt works
this is a my upload section code

optionsTake: CameraOptions = {
    quality: 100,
    destinationType: this.Camera.DestinationType.DATA_URL,    
    mediaType: this.Camera.MediaType.PICTURE,
    targetWidth: 600,
    targetHeight: 600
  }
  optionsGalery: CameraOptions = {
    quality: 100,
    destinationType: this.Camera.DestinationType.DATA_URL,
    mediaType: this.Camera.MediaType.PICTURE,   
    sourceType     : this.Camera.PictureSourceType.PHOTOLIBRARY,
    targetWidth: 600,
    targetHeight: 600
  }

takePicture(){
    console.log('masuk')
    this.Camera.getPicture(this.optionsTake).then((imageData) => {
      this.isiimage = "data:image/jpeg;base64," + imageData;
      this.base64Image = imageData;
      //console.log(this.base64Image)      
      this.postUpdatePicture(this.base64Image, this.user.user_id);
      
     }, (err) => {
      // Handle error
     });    
  }
  getPhotoFromGallery(){
    console.log('masuk')

    this.Camera.getPicture(this.optionsGalery).then((imageData) => {
      this.isiimage = "data:image/jpeg;base64," + imageData;
      this.base64Image = imageData; 
      //console.log(this.base64Image)     
      this.postUpdatePicture(this.base64Image, this.user.user_id);
     }, (err) => {
      // Handle error
     });
  }

  updatePicture() {
    let actionSheet = this.actionSheetCtrl.create({
      title: 'Pilihan',
      buttons: [
        {
          text: 'Ambil Gambar',
          role: 'ambilGambar',
          handler: () => {
            this.takePicture();
          }
        },
        {
          text: 'Pilih Dari Galleri',
          role: 'gallery',
          handler: () => {
            this.getPhotoFromGallery();
          }
        }
      ]
    });
    actionSheet.present();
  }

  postUpdatePicture(img64,userid){
    this.loading = this.loadCtrl.create({
        content: 'Uploading image...'
    });
    this.loading.present();
    let param = JSON.stringify({
        picture: img64
    });    
    this.http.post(this.userData.BASE_URL+'api/user/upload/userphoto/'+userid,param,this.options).subscribe(res => {
      this.loading.dismiss();
      let response = res.json();
      if(response.status==200) {
        //this.userData.updateProfilePict(response.picture);
        //this.user.userphoto = response.picture;
        //this.showAlert("Berhasil mengubah foto profile"); 
        this.showAlert(response.message); 
      }         
    }, err => { 
        this.loading.dismiss();
        this.showError(err);
    });
}

Please help how to pass the file image or image64base (whichonebetter?) to my node js api :frowning:
i really need finish this for college project

thanks before