Ionic 3 - save camera picture to javascript File Object for upload


#1

code

import { Component, ViewChild } from '@angular/core';
import { Platform,App, IonicPage, NavController, NavParams, ViewController, ModalController, ToastController, ActionSheetController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { Camera } from '@ionic-native/camera';
import { ConsentPage } from '../consent/consent';
import { CasesProvider } from '../../providers/cases/cases';
import { CookieService } from 'ngx-cookie-service';

import {  CameraOptions } from '@ionic-native/camera';
import { Base64 } from '@ionic-native/base64';
import { commonLib } from '../../common/common-lib';

@IonicPage()
@Component({
	selector: 'upload-case-image',
	templateUrl: 'upload-case-image.html',
})
export class UploadCaseImagePage {

	@ViewChild('fileInput') fileInput;
	consentImage;
	currentCase: any;
	isReadyToSave: boolean;
	item: any;
	caseForm: FormGroup;
	userId: string;
	uploadFile: any;
	caseId: any;
	imageURI:any;
	backgroundImg:any;
	 formData = new FormData();
	  filePath: string = 'file:///...';
	constructor(
		public navCtrl: NavController,
		public navParams: NavParams,
		public viewCtrl: ViewController,
		formBuilder: FormBuilder,
		public camera: Camera,
		public appCtrl: App,
		public modalCtrl: ModalController,
		public casesProvider: CasesProvider,
		public toastCtrl: ToastController,
		public cookieService: CookieService,
		public common:commonLib,
		public platform: Platform,
		private base64: Base64,
		public actionSheetCtrl: ActionSheetController
	) {
		this.userId = cookieService.get('userId');
		this.currentCase = this.navParams.get('currentCase');
		console.log('currentCase', this.currentCase);
		this.caseId = this.currentCase.caseId;
		console.log('case id',this.caseId);
		this.formData.append('caseId',this.caseId);
		this.formData.append('userId',this.userId);
		console.log('this.formdata',this.formData);
		this.caseForm = formBuilder.group({
			file: ['', Validators.required],
			//	consentImage:['', Validators.required]

		});
		
	
		// Watch the form for changes, and
		this.caseForm.valueChanges.subscribe((v) => {
			this.isReadyToSave = this.caseForm.valid;
		});
	}
	
	getPicture() {
		if (this.platform.is('cordova')) {
			alert('test');
			this.presentActionSheet();
		  }else{
			this.fileInput.nativeElement.click();
		  }
	
	}
	public presentActionSheet() {
		let actionSheet = this.actionSheetCtrl.create({
		  title: 'Select Image Source',
		  buttons: [
			{
			  text: 'Load from Library',
			  handler: () => {
				this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
			  }
			},
			{
			  text: 'Use Camera',
			  handler: () => {
				this.takePicture(this.camera.PictureSourceType.CAMERA);
			  }
			},
			{
			  text: 'Cancel',
			  role: 'cancel'
			}
		  ]
		});
		actionSheet.present();
	  }
	  public takePicture(sourceType) {
		// Create options for the Camera Dialog
	this.common.showLoading('');
		const options: CameraOptions = {
			quality: 100,
			sourceType: sourceType,
			destinationType: this.camera.DestinationType.DATA_URL,
			encodingType: this.camera.EncodingType.JPEG,
			mediaType: this.camera.MediaType.PICTURE
		  }
		// Get the data of an image
		this.camera.getPicture(options).then((imageData) => {
		//	alert('test image'+imageData);
		this.common.hideLoading();
			let base64Image = 'data:image/jpeg;base64,' + imageData;
			this.caseForm.controls['file'].setValue(base64Image);
			this.uploadFile = 'data:image/jpeg;base64,' + imageData;
			this.backgroundImg  = 'url(' + base64Image + ')';
			//console.log('test image'+base64Image);
		});
	}
	processWebImage(event) {
		if (!this.platform.is('cordova')) {
		let fileList: FileList = event.target.files;
		console.log('fsdfsdfdsfsxxx', fileList);
		let reader = new FileReader();
		reader.onload = (readerEvent) => {
			let imageData = (readerEvent.target as any).result;
			this.caseForm.patchValue({ 'file': imageData });
		//	console.log('imageData', imageData);
			this.backgroundImg  = 'url(' + imageData + ')';
		};
		console.log('event.target.files[0]', event.target.files[0]);
		if(event.target.files[0]!= undefined){
			reader.readAsDataURL(event.target.files[0]);
			this.uploadFile = event.target.files[0];
		}
		}
	}

	getProfileImageStyle() {
	//	console.log('getProfileImageStyle',this.caseForm.controls['file'].value);
		return 'url(' + this.caseForm.controls['file'].value + ')'
	}

	/**
	 * The user cancelled, so we dismiss without sending data back.
	 */
	cancel() {
		this.viewCtrl.dismiss();
	}
	/**
	 * The user upload image to existing case.
	 */
	uploadCaseImage() {
		
		this.formData.append('file', this.uploadFile);
		console.log('formData', this.formData);
	//	if (!this.caseForm.valid) { return; }

		this.casesProvider.uploadImage(this.formData).subscribe((res)=>{
			console.log('uploadImage res',res);

			this.navCtrl.push('MyCasesPage');
		},(error)=>{
			console.log('uploadImage error',error);
		});
		//	this.navCtrl.push(MyCasesPage);
	}
	presentConsentModal() {
		// let contactModal = this.modalCtrl.create(ConsentPage);
		// contactModal.present();
		this.navCtrl.push(ConsentPage,
			{  //TODO: case object can go here
				data: {},
				callback: this.getConsentImage
			});
	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad CreateCasePage');
	}

	getConsentImage = (data) => {
		return new Promise((resolve, reject) => {
			// for (let order of data) {
			//   // this.data = data;
			//   console.log(data);
			//   // image = data;
			// }

			console.log('back to new case page');
			console.log(data);
			this.consentImage = data;
			//this.caseForm.patchValue({ 'consentImage': 'data:image/jpg;base64,' + data });
			resolve();
		});
	};
}

send data as file object using native camera