Uploading Image from android file system to Firebase Storage - android

I am currently creating a page that allows users to take pictures of both their identity card and selfie of themselves, however, i am not able to get the files from the file system to upload it using submitpicture().
Here is my typescript code:
import { Component, OnInit } from '#angular/core';
import { File } from '#ionic-native/file/ngx';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import * as firebase from 'firebase';
import { EmailComposer } from '#ionic-native/email-composer/ngx';
import { ModalController } from '#ionic/angular';
#Component({
selector: 'app-verifyidentity',
templateUrl: './verifyidentity.page.html',
styleUrls: ['./verifyidentity.page.scss'],
})
export class VerifyidentityPage implements OnInit {
constructor(public camera: Camera, public file: File, private modalController: ModalController, public emailComposer: EmailComposer) { }
nric: any;
selfie: any;
nricimageData: any;
selfieimageData: any;
ngOnInit() {
}
takenric() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.nricimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.nric = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
takeselfie() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.selfieimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.selfie = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
submitpicture() {
firebase.storage().ref().child("nric").put(this.nric); // this does not work!
}
I was wondering if it is possible to get the image from the android system with the file path and store it in a variable before uploading to firebase storage with submitpicture().
So sorry for any inconvenience caused and thank you.
Best regards,
Dan

Related

ionic 4 (android) get image (OBJECT FILE) from gallery (FILE_URI) and upload via API

I'm trying to implement a simple application using Ionic v4 angular and cordova. Just select a photo and upload it to a parse server (back4app.com). But I couldn't do it.
This is my code:
home.page.ts
import { ParseService } from '../service/parse.service';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import { File } from '#ionic-native/file/ngx';
import { WebView } from '#ionic-native/ionic-webview/ngx';
selectPhoto() {
const options: CameraOptions = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation: true
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
// let base64Image = 'data:image/jpeg;base64,' + imageData;
// console.log(imageData);
this.fileToUpload = imageData;
this.phototoshow = this.webview.convertFileSrc(imageData);
}, (err) => {
// Handle error
});
}
onSubmit() {
this.presentLoading();
// return this.apiService.upload(this.phototoshow).subscribe((data: any) => {
return this.apiService.upload(this.fileToUpload).subscribe((data: any) => {
console.log(data);
}
}
service.ts
upload(img1): Observable<any> {
// console.log(data);
return this.http.post(this.apiURL + '/files/img.jpg', img1,{
headers: {
'X-Parse-Application-Id': this.APP_ID,
'X-Parse-REST-API-Key': this.REST_API_KEY,
'Content-Type':'image/jpeg'
}
})
.pipe(
retry(1),
catchError(this.handleError)
)
}
I was able to upload the image with "input type = file" in the form ... but selecting the image from the gallery with the cordova plugin camera ... it only returns FILE_URI but I need the OBJECT FILE to upload via api rest.
I have read enough info on the web but it is old information that does not help me. I hope someone can help me with the problem. thanks
I managed to solve the problem:
startUpload() {
this.file.resolveLocalFilesystemUrl(this.fileToUpload)
// this.file.resolveLocalFilesystemUrl(imgEntry.filePath)
.then(entry => {
(entry as FileEntry).file(file => this.readFile(file))
})
.catch(err => {
alert('Error while reading file.');
});
}
readFile(file: any) {
const reader = new FileReader();
reader.onload = () => {
const imgBlob = new Blob([reader.result], {
type: file.type
});
this.onSubmit(imgBlob);
};
reader.readAsArrayBuffer(file);
}

ionic native camera taking picture but not showing it .i want to take picture and show it on the same page

i am trying ion native camera api , thats takin picture as the camera shows up and i can click an image but tha image is not shoing up
i am using android oreo , ionic 3 and latest cordova and running app on a real device
<-- file home.html-->`
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-button round (click)="eventofClick()">Round Button</button>
<p><img src="{{image}}" /> </p>
{{image}}
</ion-content>
<--home.ts-- ------------------------------------------------------>
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
image: any;
constructor(public navCtrl: NavController, public camera: Camera) {
console.log("constructor");
}
eventofClick() {
console.log("called");
console.log('inside');
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
}
i want after taking picture i want to show it along
what i am getting as output is
and at console i am getting 1549019043619.jpg:1 GET unsafe:data:image/jpeg;base64,file:///storage/emulated/0/Android/data/com.catalyst.android.safra/cache/1549019043619.jpg 404 (Not Found)
Try it, this will return you an FILE_URI of your image. If you are uploading image to the server try to show images from your server after uploading. or You can show it directly with base 64. For Base64 you have to change destinationType: this.camera.DestinationType.FILE_URI to destinationType: this.camera.DestinationType.DATA_URL in CameraOptions.
upload Image and Show it.
takePhoto(){
const options: CameraOptions = {
quality: 80,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64 (DATA_URL):
console.log(imageData);
this.imageUpload(imageData) / pass your URL in upload function
}, (err) => {
// Handle error
});
}
imageUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'image',
fileName: '.png',
chunkedMode: false,
//mimeType: "image/jpeg",
}
fileTransfer.upload(path, 'Server_URL', options)
.then((data) => {
let res = JSON.parse(data.response);
if (res.success == true) {
//server will return you image name Push that name into an array and show it on your View
}
}, (err) => {
console.log(err);
});
}

how to launch camera in an ionic app

I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}

Photo not displayed when selected from photo library in Ionic 2

I am using Camera plugin in Ionic 2 for uploading photos. I am running the app on an Android device. The Carema capture is displayed in the app but when selected from Gallery the photo is not displayed.
The following methods are used for Camera and Gallary:
private openCamera(){
var options: CameraOptions = {
sourceType: this.camera.PictureSourceType.CAMERA,
destinationType: this.camera.DestinationType.DATA_URL,
allowEdit: true,
saveToPhotoAlbum: true
};
this.camera.getPicture(options).then((imageData) => {
this.cameraData = 'data:image/jpeg;base64,' + imageData;
this.photoTaken = true;
this.photoSelected = false;
let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
private selectFromGallery() {
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
this.cameraUrl = imageData;
this.photoSelected = true;
this.photoTaken = false;
}, (err) => {
// Handle error
});
}
Following is the code to display in HTML page:
<img [src]="cameraData" *ngIf="photoTaken">
<img [src]="cameraUrl" *ngIf="photoSelected">
You need to use a file plugin to obtain local filesystem url when you select from library.
To install:
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save #ionic-native/file
Import:
import { File } from '#ionic-native/file';
and in your code:
constructor( private file: File, .... ) {}
.....
const options: CameraOptions = {
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageURI) => {
this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => {
this.cameraUrl = fileEntry.nativeURL;
this.photoSelected = true;
this.photoTaken = false;
});
}, (err) => {
// Handle error
});
EDIT
You might need to sanitize the value for img src:
<img *ngIf="cameraUrl" [src]="sanitizeUrl(cameraUrl)" />
The function:
import { DomSanitizer } from '#angular/platform-browser';
....
constructor( private sanitizer: DomSanitizer, .... ) {}
....
sanitizeUrl(url) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}

Ionic2/Angular2 Http is not working

I am new to Ionic framework and Angular2. I am unable to send post request to the server. I can't figure out what thing I am missing.
My App code:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from 'ionic-native';
import { Http, Headers, HTTP_PROVIDERS } from 'angular2/http';
import 'rxjs/Rx';
#Component({
selector: 'page-upload',
templateUrl: 'upload.html'
})
export class UploadPage {
public base64Image: string;
array = Array<any>;
loading: boolean;
constructor(public navCtrl: NavController,public http: Http) {
}
takePicture(){
Camera.getPicture({
destinationType: Camera.DestinationType.DATA_URL,
targetWidth: 1000,
targetHeight: 1000
}).then((imageData) => {
// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
console.log(err);
});
}
accessGallery(){
Camera.getPicture({
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: Camera.DestinationType.DATA_URL
}).then((imageData) => {
this.base64Image = 'data:image/jpeg;base64,'+imageData;
}, (err) => {
console.log(err);
});
}
makePostRequest() {
this.http.get('https://public-api.wordpress.com/rest/v1.1/freshly-pressed/').subscribe(data => {
});
}
}
When I compile the app for android I get the following error:
L16: constructor(public navCtrl: NavController,public http: Http) {
Cannot find name 'Http'.
I checked one of my Ionic 2 projects and your imports should be
import {Http, Headers, RequestOptions, Response} from '#angular/http';
check your package.json and fix your project dependencies. You could use this project for references
https://github.com/driftyco/ionic-conference-app/blob/master/package.json

Categories

Resources