Uncategorized

Upload image

A complete example on how to use Ionic and PHP to upload image from your app to the server .

You can display the image once selected on your Html file and delay the upload to the last step when you ready to send all your form data ,start by uploading your image and when success return call the remaining data post method and add your upload image name with these data .

PHP Server code

public function addWord(Request $request, Response  $response) 

{

    $this->request=$request;

    $this->response=$response;

    $inputs = $request->getParsedBody();

    $title=$inputs[‘title’];

    $catId=$inputs[‘catId’];

    $identfier=$inputs[‘identfier’];

    $pathToUpload=$this->pathToUpload;

    $thumbSmallWidth=$this->imgSmallWidth;

    $requestSmallThumb=true ;

    $uploadedFiles = $request->getUploadedFiles();

    if (empty($uploadedFiles[‘newfile’])) {

            echo “no files”;

        }

    $file = $uploadedFiles[‘newfile’];

    $extension = strtolower(pathinfo($file->getClientFilename(), PATHINFO_EXTENSION));

    $basename = time(); 

    $filename = sprintf(‘%s.%0.8s’, $basename, $extension);

    $folderName=”;

    $src=”../$pathToUpload/original/$filename”;

    $file->moveTo($src);

    $thumbSmallDest=”../$pathToUpload/words/$filename”;

    crudController::createThumb($src,$thumbSmallDest,$thumbSmallWidth,false);

 //——-Add to database

        $sql=”insert into words (title,catId,img,identfier) values (‘$title’,$catId,’$filename’,$identfier)”;

       $sth = $this->db->prepare($sql);

       try{

           $sth->execute();

            $responseData = array();

            $responseData[‘error’] = false; 

            }

       catch (\PDOException $e) {

            $responseData = array();

            $responseData[‘error’] = true; 

            $responseData[‘errorCode’] =  $e->getMessage(); 

            $responseData[‘sql’] = $sql; 

            }

       return $this->response->withJson($responseData);

}

Ionic Code :

.html file :                    

<div class=”img_cover ” margin-bottom [ngClass]=”{‘conatin_img’ : img!=”}”>

<button ion-button color=”primary” (click)=” selectImage() “>

<ion-icon name=”md-images” color=”light”></ion-icon>

</button>

<img *ngIf=”img” [src]=”domSanitizer.bypassSecurityTrustUrl(img)”>

</div>

<button ion-button color=”primary” (click)=” selectImage() “>

.ts file :


import { FileTransfer, FileUploadOptions, FileTransferObject } from ‘@ionic-native/file-transfer’;

import { File } from ‘@ionic-native/file’;

  imageURI: any;

if (this.imageURI) {

  const fileTransfer: FileTransferObject = this.transfer.create();

  let options: FileUploadOptions = {

    // mimeType: ‘multipart/form-data’,

    httpMethod: ‘POST’,

    fileKey: ‘newfile’,

    chunkedMode: false,

    params:

      {

        title: ‘aaaaaa’,

        catId: ‘1’

      },

    headers: {}

  }

  fileTransfer.upload(this.imageURI, ‘http://xxxxxxx/api/uploadFile’, options)

    .then((result) => {

}, (err) => {

      this.global.dismissCustomLoading();

      console.log(err);

    });

}

 selectImage() {

    let actionSheet = this.actionSheetCtrl.create({

      title: ‘Modify your Picture’,

      buttons: [

        {

          text: ‘Gallery’,

          handler: () => { this.getImage(1); }

        }, {

          text: ‘Camera’,

          handler: () => { this.getImage(2); }

        }, {

          text: ‘Cancel’,

          role: ‘cancel’,

          handler: () => { }

        }

      ]

    });

    actionSheet.present();

  }

  getImage(source) {

    const options: CameraOptions = {

      quality: 100,

      destinationType: this.camera.DestinationType.FILE_URI,

      encodingType: this.camera.EncodingType.JPEG,

      mediaType: this.camera.MediaType.PICTURE,

      allowEdit: true,

      targetWidth: 200,

      targetHeight: 200,

      correctOrientation: true

    }

    if (source == 1) {

      options.sourceType = this.camera.PictureSourceType.PHOTOLIBRARY

    }

    else {

      options.sourceType = this.camera.PictureSourceType.CAMERA

    }

    this.camera.getPicture(options).then((imageData) => {

      console.log(“Image::” + imageData);

      this.imageURI = imageData;

      //this.img = normalizeURL(imageData);

      let win: any = window; // hack ionic/angular compilator

      this.img = win.Ionic.WebView.convertFileSrc(imageData);

    }, (err) => {

      console.log(err);

    });

  }