Skip to main content
tags editadas
Link
Shog9
  • 101
  • 10
Fonte Link
Luiz Felipe
  • 464
  • 7
  • 22

ionic2 - upload de foto via servidor

Seguinte galera.

Tenho um aplicativo em ionic 2. A ação é simples: tirar uma foto ou selecionar uma foto da galeria. Até ai tudo bem. porém, na hora de realizar o upload, ele vai no servidor, mais a foto não vai, ou seja, o $_FILES esta vazio. vou postar abaixo o código:

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>