Ionic 2 : Envoie d'une image vers un serveur web à l'aide de PHP et Angular 2

android, ios, ionic 2

objectif



  • Accès à la Galerie & Choisissez Image
  • Obtenir la photo avec base64 string
  • Convertir base64 string à  une image visualisable

Étapes à suivre

1. Créer un nouveau projet ionic 2

ionic start sendimage --v2

2. Ajouter la plate-forme requise

ionic platform add android
ionic platform add ios

3. Ajoutez cordova Camera Plugin



ionic plugin add cordova-plugin-camera

4. Ouvrez src / pages / home / home.html et mettez ce code :

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
 <button ion-button color="primary" (click)="accessGallery()">Open Gallery</button>
 <img [src]="base64Image" *ngIf="base64Image" />
 <button ion-button color="danger" (click)="upload()">Upload</button>
</ion-content>

5. Modifiez src/pages/home/home.ts


import { Component } from '@angular/core';


import { LoadingController, AlertController } from 'ionic-angular';
import { Camera, Transfer } from 'ionic-native';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  base64Image;
  fileID="";
    constructor(
      public loadingCtrl: LoadingController,
      public alertCtrl: AlertController
    ) {}

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

    upload(){
  const fileTransfer = new Transfer();
  var options: any;
  var filename = this.base64Image.substr(this.base64Image.lastIndexOf('/') + 1) +'img.jpg';
  options = {
      fileKey: 'file',
      fileName: filename,
    // fileName: 'image.jpg',
     mimeType: "binary/octet-stream",
    // headers: {}
     params: { 'fileName': filename }
  };
  let loading = this.loadingCtrl.create({content:"Loading..."});
  loading.present();
  fileTransfer.upload(this.base64Image, encodeURI("http://yourPhpfilepath.com"), options)
   .then((data) => {
     loading.dismiss();
     console.log("Successful upload...");
     console.log("Code = " + data.responseCode);
     this.fileID= data.response;
   }, (err) => {
     // error
     loading.dismiss();
     let alert = this.alertCtrl.create({
        title: 'Cannot upload',
        subTitle: err.code,
        buttons: ['Dismiss']
      });
    alert.present();
     console.log("Failed to upload...");
     console.log("Code = " + err.code);
   })
}
  }


6. Developpez le code PHP 


<?php
header('Access-Control-Allow-Origin: *');
$target_path = "image/";
if(isset($_FILES['file']))
{
$target_path = $target_path . basename( $_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) 
{
    echo "Upload and move success";
} else 
{
echo $target_path;
    echo "There was an error uploading the file, please try again!";
}
}
?>

Commentaires

  1. well done Mr thanks a lot , the image is stored succesfully , i would like to store it into a database table and display it with ionic list . Which changes to the php code??

    RépondreSupprimer
    Réponses
    1. You cannot store an image into a database... but you can insert its URL into the database. And after that you can retrieve the images in a List from their URLs

      Supprimer

Enregistrer un commentaire

Your comment will be reviewed by moderators

Posts les plus consultés de ce blog

Premier tutoriel avec Arduino et Proteus ISIS

Login et password ,formulaire d'authentification sous android avec mysql et json

Connexion d'une application Android et une base de données externe Mysql avec web services php Json (opérations CRUD)