IOnic 2 RC1: How to Upload photo from Gallery to server


#1

Hi,

Please guide me how to upload a image to server using API by picking image from gallery in Ionic 2 Rc1.

what steps are involved for doing that?

Thanks!


Image upload from gallery to server using ionic 2
#2

simple:

  • ionic-native is already installed
  • cordova camera is already installed

use the camera:

To get a photo out of the library instead of taking a picture --> you can set the sourceType in camera options:


#3

thanks, but i don’t understand how can i give image upload option in my template(for example: by giving user a button by using that button user can upload and which function i need to call upon click of that button).

please explain a bit more and i also want to post that image using http post call.

thanks again!


#4

okay if you do not know… how to handle a click… you should read some angular2 tutorials.

<button (click)="callMyAction()">Take photo</button>

in your component

class XXX {

  callMyAction() {
     // options = {sourceType: 0}
    Camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      let base64Image = 'data:image/jpeg;base64,' + imageData;
    }, (err) => {
      // Handle error
    });
  }
}

and do not forget to wait until cordova is ready


#5

Thank you very much!


#6

when i am sending base64Image to server in post request it giving me below error, what will be the reason?


#7

you are producing invalid json data.
show us some code of your upload request.

why sending base64? You could get the image path instead of base64 representation.
So you would use the cordova-file-transfer plugin.


#8

Thanks!

Here is Image Picker code.

ImagePick() {
let options = {
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.PHOTOLIBRARY
};
Camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it’s base64:
this.base64Image = ‘data:image/jpeg;base64,’ + imageData;
console.log(this.base64Image);
}, (err) => {
// Handle error
});
}

Here i am calling the Sign_up function:

this.user_service.Sign_up(this.myForm.controls.email.value, this.myForm.controls.password.value,
** this.myForm.controls.password_confirmation.value, this.myForm.controls.first_name.value, this.myForm.controls.last_name.value**
** , this.myForm.controls.address.value, this.myForm.controls.city_id.value, this.myForm.controls.phone.value,this.base64Image)**
.subscribe(result => {

          if(result == true) {

              Toast.show("Account Successfully created!", 'long', 'top').subscribe(
                  toast => {
                    console.log('Success', toast);
                  },
                  error => {
                    console.log('Error', error);
                  }
              );

              this.navCtrl.setRoot(LoginPage)

          }else {
            // login failed
            //console.log("coming in........");
            this.error = 'Email Already registered';
            //  this.loading = false;
          }
        }, error => {
          console.log(JSON.stringify(error.json()));
          this.error = 'Email Already registered please try another';
        });
  }else{

    this.error2="Password and Confirm password should be same";

  }

and here is Post request.

Sign_up(email, password, confirmation_password, first_name, last_name, address, city_id, phone, img) {

    let body = JSON.stringify({
        email: email, password: password, confirmation_password: confirmation_password,
        first_name: first_name, last_name: last_name, address: address, city_id: city_id, phone: phone, img: img
    });

     console.log(body);

    return this.http.post(this.SIGN_UP_URL, body, {headers: this.contentHeader})
        .map((response:Response) => {

        // console.log(response);

        if (response.status == 200) {

            ///console.log(response);
            return true;
        } else {
            return false;
        }
    });
}

#9

Hi,

now i am send path to server using “NATIVE_URI” but still image is not uploading, waiting for your quick response.

Thanks!


#10

you can not simple send the url you need the cordova file transfer plugin then


#11

How can i do that?

another thing is i want to send that in http.post request is it possible? if not please guide me how to do that i urgently need for that in my project…

Thanks!


#12

maybe you ask google for the cordova file-transfer plugin…
i will not implement the solution for you ;).

There are many examples for this use case.


#13

nice! but i am asking for, is it possible to send image file in http post?


#14

check

the

documentation

of

cordova-file-transfer

-.-


#15

Check your folder attributes in the server. It might be restricted by their serverside if you haven’t made any mistake at client side. Try using 777 for folder attributes.
Below link might helpful for you.


#16

The way I did this:

  • install Cordova file plugin
  • install Cordova file transfer plugin
  • use regular input type file in your HTML
  • using html5 file Api get instance of file
  • put it temporary directory (in case of large files your app will crash if you use base64; large is about 20 Mb)
  • then use file transfer plugin with chunk mode which sends file to server in binary format

#17

can you share your code for uploading, i am having issue with uploading file to server.

thanks!


#18

I would create a whole FormData --> and grab all files from the existing form and append them to the form:
https://developer.mozilla.org/de/docs/Web/API/FormData/append

you can send the whole FormData object to your server.


#19

Hi,

Sorry for the late response. I created gist for now: https://gist.github.com/stalniy/5bc1d59bdb69a605ff6ebef036729abb

Probably later will create a library for this

@Inject is just my alternative to inject Angular2 dependencies in ES6/7 way (looks better than strange static array of arrays).
import { Events } from 'events' is just global event bus
Config is a service which represents application configuration


#20

Thanks! i will ping you back, if need further guidance.
:slight_smile:

Thanks again!