Skip to content

Instantly share code, notes, and snippets.

@coolvasanth
Last active June 29, 2021 01:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save coolvasanth/ab61fc337e6561be4559171b74221b1a to your computer and use it in GitHub Desktop.
Save coolvasanth/ab61fc337e6561be4559171b74221b1a to your computer and use it in GitHub Desktop.
pick image from gallery or from camera and upload it to server via API, ionic 2
//install camera, file trnasfer plugin from ionic native and it's providers in app.component.ts. then only you can use thse codes in your .ts file.
presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
title: 'Pick your profile photo',
buttons: [
{
text: 'From Gallery',
handler: () => {
this.openGallery();
}
},
{
text: 'From Camera',
handler: () => {
this.opencamera();
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}
]
});
actionSheet.present();
}
openGallery() {
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
const fileTransfer: TransferObject = this.transfer.create();
let options1: FileUploadOptions = {
fileKey: 'image_upload_file',
fileName: 'name.jpg',
headers: {},
params: {"app_key":"Testappkey"},
chunkedMode : false
}
fileTransfer.upload(imageData, 'your ApI that can take image', options1)
.then((data) => {
// success
alert("success"+JSON.stringify(data));
}, (err) => {
// error
alert("error"+JSON.stringify(err));
});
});
}
opencamera()
{
let options = {
quality: 100
};
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
const fileTransfer: TransferObject = this.transfer.create();
let options1: FileUploadOptions = {
fileKey: 'image_upload_file',
fileName: 'name.jpg',
headers: {},
params: {"app_key":"Testappkey"},
chunkedMode : false
}
fileTransfer.upload(imageData, 'your ApI that can take imageyour ApI that can take image', options1)
.then((data) => {
// success
alert("success"+JSON.stringify(data));
}, (err) => {
// error
alert("error"+JSON.stringify(err));
});
});
}
@coolvasanth
Copy link
Author

finished

@Quixotical
Copy link

and what would you do if you have the image URI instead of base64? I had read that it's problematic for performance to try to process the base64 string

@coolvasanth
Copy link
Author

The above code works fine for both File URI and Base 64. If you can elaborate how exactly it affects the performance (or give some URL where you have read). I could evaluate it further.

@kapilSoni101
Copy link

kapilSoni101 commented Mar 7, 2020

@coolvasanth: sir I got "Failed to load resource error during image capture from camera and store to db but if am upload from Gallery it's working.cam y tell m how to fix?

@coolvasanth
Copy link
Author

Hi @kapilSoni101 can you give more details about the issue. Which device, platform your using ? what is the output after capturing the image ?
For a quicker response you can also reach me at my facebook group. https://www.facebook.com/groups/860600517451989/?ref=bookmarks

@kapilSoni101
Copy link

Hi @coolvasanth:
1.sir during image upload camera i got below error only if upoad image from camera but in case of library its working properly.below i will share the code snippt.
2. I have tested in Nokia 7 and platform is android.
3. i got below output after capturing the image.

> ` let options: FileUploadOptions = {
>       fileKey: "file",
>      fileName: this.lastImage,
>      chunkedMode: false,
>       mimeType: "multipart/form-data"
>      , headers:{"userid":this.userId,"token":this.token}
>      ,params :  postDate
>       }`

Failed to load resource: the server responded with a status of 404.
can you tell me what the problem ?

@coolvasanth
Copy link
Author

After capturing the image are you able to log the path of it ? is capturing process working fine ?

@kapilSoni101
Copy link

kapilSoni101 commented Mar 8, 2020

Yes sir I have properly get image path and image capture is properly.
I Saw ur capture image code,can u tell me why ur not using "mimeType" in ur code?

@coolvasanth
Copy link
Author

If you are able upload image properly from Gallery but it is failing from camera because of 404 issue means, somewhere program is not able to access the captured image. Did u try converting the captured Image path to native URL with cordova-plugin-filepath

@kapilSoni101
Copy link

Yes sir I have already used native URL with filepath plugin but same result.
Last msg I have asked a question:-
ur not using "mimeType" in ur code.can u explain me why?

@coolvasanth
Copy link
Author

Hi, It's long ago I had created this Gist, so I'm finding difficulty in recalling why mimeType is not used. If all the things are correct but still your not able to upload the image captured from camera means, I would suggest you this repository of mine.

  1. Convert image captured from camera to base64 format.
  2. Ensure Image is converted to base64 format by logging the output of the base64 plugin.
  3. Upload base64 to server and convert it into Image file there. All the modern programming language has support to convert base64 into actual file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment