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

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!

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:

1 Like

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!

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

1 Like

Thank you very much!

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

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.

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;
        }
    });
}

Hi,

now i am send path to server using ā€œNATIVE_URIā€ but still image is not uploading, waiting for your quick response.

Thanks!

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

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!

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.

1 Like

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

check
ā€¦
the
ā€¦
documentation
ā€¦
of
ā€¦
cordova-file-transfer

-.-

3 Likes

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.

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

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

thanks!

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.

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

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

Thanks again!