Ionic 2 Problem with uploading picture to PHP server


#1

Hi, I’ve been struggling with uploading pictures made in ionic2 app to PHP server.
The camer plugin is working fine, my app is able to make a photo and select one from the gallery. I have problem with uploading that photo to my PHP server. any help maybe?


#2

Try to put yourself in the position of somebody who is trying to help you. What information would you ask for beyond “I have problem”?


#3

sorry,my fault… I will post my code


#4

I am completely new to Ionic 2
This is my code for making pictures and selecting from gallery

import {Component} from '@angular/core';
import { Camera, File, Transfer, FilePath } from 'ionic-native';
import {DomSanitizer} from '@angular/platform-browser';
import { NavController, ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular';
declare var cordova: any;

@Component({
  selector: 'page-camera',
  templateUrl: 'camera.html'
})
export class CameraPage {
  cameraData: string;
  photoTaken: boolean;
  cameraUrl: string;
  photoSelected: boolean;
  lastImage: string = null;
  loading: Loading;
base64Image
  constructor(private navCtrl: NavController, private _DomSanitizationService: DomSanitizer,public toastCtrl: ToastController,public loadingCtrl: LoadingController) {
    this.photoTaken = false;
  }

 accessGallery(){
    Camera.getPicture({
      sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
      destinationType: Camera.DestinationType.DATA_URL
    }).then((imageData) => {
	this.cameraUrl = imageData;
      this.photoSelected = true;
      this.photoTaken = false;
        this.base64Image = 'data:image/jpeg;base64,'+imageData;
    }, (err) => {
        console.log(err);
    });
  }
openCamera() {
    var options = {
      sourceType: Camera.PictureSourceType.CAMERA,
      destinationType: Camera.DestinationType.DATA_URL
    };
    Camera.getPicture(options).then((imageData) => {
      this.cameraData = 'data:image/jpeg;base64,' + imageData;
      this.photoTaken = true;
      this.photoSelected = false;
    }, (err) => {
      // Handle error
    });
  }

and this one is for uploading the picture to PHP server

public pathForImage(img) {
  if (img === null) {
    return '';
  } else {
    return cordova.file.dataDirectory + img;
  }
}
private copyFileToLocalDir(namePath, currentName, base64Image) {
  File.copyFile(namePath, currentName, cordova.file.dataDirectory, base64Image).then(success => {
    this.lastImage = base64Image;
  }, error => {
    this.presentToast('Error while storing file.');
  });
}
  public uploadImage() {
  // Destination URL
  var url = "http://my-ecarguide.000webhostapp.com/api/upload.php";
 
  // File for Upload
  var targetPath = this.pathForImage(this.lastImage);
 
  // File name only
  var filename = this.lastImage;
 
  var options = {
    fileKey: "file",
    fileName: filename,
    chunkedMode: false,
    mimeType: "multipart/form-data",
    params : {'fileName': filename}
  };
 
  const fileTransfer = new Transfer();
 
  this.loading = this.loadingCtrl.create({
    content: 'Uploading...',
  });
  this.loading.present();
 
  // Use the FileTransfer to upload the image
  fileTransfer.upload(targetPath, url, options).then(data => {
    this.loading.dismissAll()
    this.presentToast('Image succesful uploaded.');
  }, err => {
    this.loading.dismissAll()
    this.presentToast('Error while uploading file.');
  });
}
}

#5

That helps.

Is there anything in the server logs that looks useful? What error is returned? Are we certain that the server is expecting multipart/form-data (and not JSON, for example)? Are we sure that what the client is sending is what the server is getting?


#6

Thanks for quick reply,
so the problem is when I take a picture using Ionic app and then click to upload it, I got error 'Error while uploading file.'
The server doesn’t receive anything.

I based my code on this website.

https://devdactic.com/ionic-2-images/

the php looks like this

<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
 
$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!";
}
?>

thats my html for Ionic

<ion-header>
  <ion-navbar>
  <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding class="home">
  
  <button ion-button color="secondary" round (click)="openCamera()">Open camera</button>
  <button ion-button color="primary" (click)="accessGallery()">Open Gallery</button>
  <button ion-button icon-left (click)="uploadImage()" >
        <ion-icon name="cloud-upload"></ion-icon>Upload
      </button>
	  <img [src]="_DomSanitizationService.bypassSecurityTrustUrl(cameraData)" *ngIf="photoTaken">

  <img [src]="base64Image" *ngIf="base64Image" />
</ion-content>

#7

That makes me suspect a CORS issue. Maybe this might have some useful information.


#8

I did check again and there is a folder for the pictures uploads on my server but it is empty, app can connect to PHP server via CORS. The problem is somewhere in the Ionic code. I did install
cordova-plugin-file ,cordova-plugin-file-transfer ,cordova-plugin-filepath but no luck.


#9

Do you get any errors anywhere? Right now it sounds like a bit like you are jumping to conclusions.


#10

It was my suggestion, the code for taking picture and selecting one from gallery works ok,
Yes when I run an app in the browser and try to upload a picture I got this error


I am new to Ionic2 and I think my code is probably wrong.
Maybe anyone has a working example of taking a picture and uploading it to php server?


#11

https://devdactic.com/ionic-2-images/


#12

The code from that website is not working properly for me,it does not take a photo or select one from gallery either.


#13

Hi Jakub,
How are you getting namePath and currentName for copyFileToLocalDir method?
I am stuck to upload file to server.

Thank you in Advance.