ionic2 - photo upload via server

Asked

Viewed 503 times

0

Following guys.

I have an application in Ionic 2. The action is simple: take a photo or select a photo from the gallery. So far so good. however, at the time of uploading, it will go on the server, but the photo will not, IE, the $_FILES is empty. I will post below the code:

import { Component } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { NavController, AlertController,  } from 'ionic-angular';
import { Camera, Base64ToGallery, Transfer, FileUploadOptions } from 'ionic-native';
import { AuthProvider } from '../../providers/auth-provider';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  private imageCam: string;
  private imageGal: string;
  private imgName: string = 'IMG';
  private camOptG = {
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
    DestinationType: Camera.DestinationType.FILE_URI,
    quality: 100,
    correctOrientation: true,
    allowEdit: true,
    targetWidth: 1000,
    targetHeight: 1000
  };
  private camOptC = {
    sourceType: Camera.PictureSourceType.CAMERA,
    DestinationType: Camera.DestinationType.FILE_URI,
    quality: 100,
    correctOrientation: true,
    allowEdit: true,
    targetWidth: 1000,
    targetHeight: 1000
  };
  Base: any;
  bytesSent: any;
  fileTransfer: any = new Transfer();

  constructor(public navCtrl: NavController, private alertCtrl: AlertController, private auth: AuthProvider) {

  }

  getPicture(N: string)
  {
    let opt: any = (N === 'Galeria') ? this.camOptG : this.camOptC;

    Camera.getPicture(opt).then(
      imageData => {
        this.OnSucPhoto(imageData);
      },
      err => {this.showError(err)}
    );
  }

  OnSucPhoto(imageData) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Content-Type', 'multipart/form-data');

    let serverUrl = 'http://meuendereco/get.php';
    this.showError(serverUrl);

    this.fileTransfer.upload(encodeURI(imageData), serverUrl, {
      headers: headers,
      fileKey: 'file',
      fileName: imageData.substr(imageData.lastIndexOf('/') + 1),
      mimeType: 'image/jpeg'
    })
      .then(
        response => {
          this.Base = JSON.stringify(response);
          this.showError(this.Base);
        }
        , err => { this.showError('Erro: '+err.body); }
      );

    //this.showError('data:image/jpeg;base64,' + imageData);
    //this.setBase64(imageData);
  }

  setBase64(base64Data) {
    let usr = JSON.parse(window.localStorage.getItem('usuario'));
    Base64ToGallery.base64ToGallery(base64Data, this.imgName+usr.id+'_').then(
      path => {console.log('Saved image to gallery ', path); this.Base = path; this.showError(path);},
      err => console.log('Error saving image to gallery ', err)
    );
  }

  showError(text) {
    let alert = this.alertCtrl.create({
      title: 'Base64 Resposta',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present();
  }

}
<?php
	if (isset($_SERVER['HTTP_ORIGIN'])) {
		header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
		header('Access-Control-Allow-Credentials: true');
		header('Access-Control-Max-Age: 86400');    // cache for 1 day
	}

	// Access-Control headers are received during OPTIONS requests
	if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
		if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
		header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

		if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
		header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

		exit(0);
	}

	$data = file_get_contents("php://input");
	$objData = json_decode($data);

  //print_r(json_encode($_FILES));
  $new_image_name = urldecode($_FILES["file"]["name"]);

  //Move your files into upload folder
  move_uploaded_file($_FILES["file"]["tmp_name"], "PastaDasFotos/".$new_image_name);

	echo json_encode($_FILES);
?>
<ion-fab right bottom>
      <button ion-fab color="primary"><ion-icon name="md-add"></ion-icon></button>
      <ion-fab-list side="left">
        <button ion-fab color="danger" (click)="getPicture('Camera')"><ion-icon name="md-camera"></ion-icon></button>
        <button ion-fab color="dark" (click)="getPicture('Galeria')"><ion-icon name="md-photos"></ion-icon></button>
      </ion-fab-list>
    </ion-fab>

2 answers

1


Try to adjust the options. I think httpMethod should fix it. When I used (successfully) this plugin, it was not necessary to use headers.

let opcoes: FileUploadOptions = {
    chunkedMode: false,
    fileKey: 'foto',
    fileName: 'foto.jpg',
    headers: {},
    httpMethod: 'POST',
    mimeType: 'image/jpeg',
    params: {}
};

transfer.upload(imageData, serverUrl, opcoes)...

0

If you use "DATA_URL" and take the Base64 image instead of its path with "FILE_URI", you can send this image via http post, it will be much easier to implement in your code and also test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.