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
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 !
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With