4

I'm building an app with Ionic 2 and Django Rest Framework. I need to take a photo from gallery or camera and upload this picture to my server.

I have this code that opens the camera and takes a picture.

options = {}
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) => {
}); 

But I don't know where it saves the pictures or how can I send it to the server. I don't find anything on Internet.

Thanks

Marcos Aguayo
  • 6,840
  • 8
  • 28
  • 61

5 Answers5

6

In IONIC 2 you will do something like this to get picture from gallery or camera (by changing source type). it will give you that image in base64 string format.

pickPicture(){

  Camera.getPicture({
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType     : Camera.PictureSourceType.PHOTOLIBRARY,
      mediaType: Camera.MediaType.PICTURE
  }).then((imageData) => {
    // imageData is a base64 encoded string
      this.base64Image = "data:image/jpeg;base64," + imageData;
  }, (err) => {
      console.log(err);
  });
}

now you can send this base64 string to server using HTTP request like this.

private http: Http
this.http.post("http://localhost:3000", this.base64Image)
                           .map((res:Response) => res.json())
                           .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

after receiving it on server side, you can decode it and do whatever you want to, like this.

 Base64.decode64(image_data[:content])

i hope it will help !

M. Habib
  • 623
  • 1
  • 9
  • 15
2

NOTE / EDIT : This code if for AngularJS, formerly known as Angular. I will leave the showcase for those who google and stumble upon this searching for Angular 1.x. solutions

RANT: (The whole idea of renaming Angular 1.x into AngularJS and after, naming Angular2 with Angular is one of most idiotic things I saw recently. Angular 2 and 4 should be named Angular2 and Angular4, Angular 1.x should have remained Angular) /end of rant

Example is a working code in one of our apps, should illustrate what I mean

$scope.takePicture = function(type) {
            if (typeof(Camera) != 'undefined') {
                var photoType = Camera.PictureSourceType.CAMERA;
                if (type == 'gallery') {
                    photoType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
                }
                var options = {
                    quality : 80, // Damir sa 75
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : photoType,
                    allowEdit : false, // Damir (true -> false)
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 625, //Damir sa 600
                    targetHeight: 800, //Damir sa 600
                    // popoverOptions: CameraPopoverOptions - Damir
                    saveToPhotoAlbum: false,
                    correctOrientation: true
                };



                $cordovaCamera.getPicture(options).then(function(imageData) {
                      $scope.images.push({slikaB64:imageData,opis:null});              
                    }, function(err) {              
                      //alert(JSON.stringify(err));
                    });
            }
            else
                $scope.images.push({slikaB64:"R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==",opis:'123'})
        }
DanteTheSmith
  • 2,937
  • 1
  • 16
  • 31
  • I'm using Ionic 2. This code doesn't work. How can I upload this picture to my server? Camera.DestinationType.DATA_URL saves the image on the phone right? – Marcos Aguayo Mar 31 '16 at 10:16
  • Once you have the file, you can upload it using this? Hope this helps with 2nd part of your question: https://docs.djangoproject.com/ja/1.9/topics/http/file-uploads/ – DanteTheSmith Apr 01 '16 at 08:26
  • 1
    The solution code provided targets Ionic v. 1 and not v. 2. – pjmolina Jan 26 '17 at 11:17
2

This is how you capture and save/ cache the image.

Camera.getPicture({
  destinationType: Camera.DestinationType.FILE_URI,
  targetWidth: 1000,
  targetHeight: 1000
}).then((imageData) => {
    this.image = imageData;
}, (err) => {
  console.log(err);
});

Right after you have taken the picture you need to upload the image.

var url = "http://your_post_url/";
var targetPath = this.image;
var filename = this.createUniqueFileName();
var options = {
  fileKey: "file",
  fileName: filename,
  chunkedMode: false,
  mimeType: "multipart/form-data",
  params : {
    "image": targetPath
  }
};
const fileTransfer = new Transfer();
fileTransfer.upload(targetPath, url, options).then(data => {
  console.log(data);
}, err => {
  console.log(err);
});
Thomas T.brhan
  • 63
  • 2
  • 10
1

To upload image to the server using Ionic 2 Framework, you have to use the Transfer plugin. Install transfer plugin using

ionic plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/transfer

Then call the upload function from Transfer class.

const fileTransfer: TransferObject = this.transfer.create();

  let options1: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}

  }

 fileTransfer.upload(imageDataLocalURL, 'http://localhost/ionic/upload',  options1)
.then((data) => {
 // success
 alert("success");
}, (err) => {
 // error
 alert("error"+JSON.stringify(err));
});

Use the link to know more https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin

Bharathiraja
  • 1,949
  • 20
  • 19
0

In the options please set the option saveToPhotoAlbum as true as shown below.

options = {
saveToPhotoAlbum: true
}

(Also you could modify the destinationType too).

Please have a look here to view the options available.

Hope this helps you. Thanks.

Raja Yogan
  • 918
  • 8
  • 17
  • My question is, how can I upload a picture to my server. You know how can I do that? – Marcos Aguayo Mar 31 '16 at 10:17
  • To upload I guess you need to do a xhr post request. (XMLHttpRequest), and send the file as formdata. Please have a look here - http://stackoverflow.com/questions/32423348/angular2-post-uploaded-file. Hope this helps you. Thanks.. – Raja Yogan Mar 31 '16 at 10:32