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

5 Answers 5

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 !

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@MarcosAguayo did i answer your question. there are two ways to upload through FILE_URL or FILE_DATA
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'})
        }

3 Comments

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?
Once you have the file, you can upload it using this? Hope this helps with 2nd part of your question: docs.djangoproject.com/ja/1.9/topics/http/file-uploads
The solution code provided targets Ionic v. 1 and not v. 2.
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

Comments

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.

2 Comments

My question is, how can I upload a picture to my server. You know how can I do that?
To upload I guess you need to do a xhr post request. (XMLHttpRequest), and send the file as formdata. Please have a look here - stackoverflow.com/questions/32423348/…. Hope this helps you. Thanks..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.