使用IONIC原生文件上传文件

时间:2018-03-14 10:05:24

标签: angular ionic-framework ionic2 ionic3

简要说明:我正在尝试使用android中的离子本机,问题是,在控制台中它说[对象]已成功上传,但我的服务器上没有上传任何内容。

  

我在浏览器中检查了网络标签,它甚至没有调用上传网址。请检查下面的代码。

下面是我的home.html代码:

<ion-content padding>
  <ion-item>
    <p>{{imageURI}}</p>
    <button ion-button color="secondary" (click)="getImage()">Get Image</button>
  </ion-item>
  <ion-item>
    <h4>Image Preview</h4>
    <img src="{{imageFileName}}" *ngIf="imageFileName" alt="Ionic File" width="300" />
  </ion-item>
  <ion-item>
    <button ion-button (click)="uploadFile()">Upload</button>
  </ion-item>
</ion-content>

home.ts 代码:

import { Component } from '@angular/core';
import { NavController, LoadingController, ToastController } from 'ionic-angular';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { Camera, CameraOptions } from '@ionic-native/camera';

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

  imageURI:any;
  imageFileName:any;

  constructor(public navCtrl: NavController,
    private transfer: FileTransfer,
    private camera: Camera,
    public loadingCtrl: LoadingController,
    public toastCtrl: ToastController) {}

  getImage() {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
    }

    this.camera.getPicture(options).then((imageData) => {
      this.imageURI = imageData;
    }, (err) => {
      console.log(err);
      this.presentToast(err);
    });
  }

  uploadFile() {
    let loader = this.loadingCtrl.create({
      content: "Uploading..."
    });
    loader.present();
    const fileTransfer: FileTransferObject = this.transfer.create();

    let options: FileUploadOptions = {
      fileKey: 'ionicfile',
      fileName: 'ionicfile',
      chunkedMode: false,
      mimeType: "image/jpeg",
      headers: {}
    }

    fileTransfer.upload(this.imageURI, 'http://example.com/upload2.php', options)
      .then((data) => {
      console.log(data+" Uploaded Successfully");
     // this.imageFileName = "http://192.168.0.7:8080/static/images/ionicfile.jpg"
      loader.dismiss();
      this.presentToast("Image uploaded successfully");
    }, (err) => {
      console.log(err);
      loader.dismiss();
      this.presentToast(err);
    });
  }

  presentToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 6000,
      position: 'bottom'
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }

}

2 个答案:

答案 0 :(得分:0)

这是因为您没有使用Exact API调用。

在代码中:fileTransfer.upload(this.imageURI, 'http://example.com/upload2.php', options)

您必须使用Api调用,该调用指向您的api端点。

尝试阅读有关api调用的更多信息。

代替http://example.com/upload2.php 你的电话应该 就像http://example.com/upload2.php/api/uploadmyimage一样,在upload2.php中,您为/api/uploadmyimage定义了get或post方法

答案 1 :(得分:0)

这是对我有用的脚本!

以html

<input type="file" name="file"  (change)="upload($event)" />

在ts文件中

upload(str:any)
  {
    const formData = new FormData();

    this.image=str.target.files[0];

    formData.append('files[]', this.image);
    console.log(formData,this.image);
    this.http.post("http://localhost/test/test.php",formData)
    .subscribe((data:any)=>{
      console.log(data);
    })
    console.log(str);
  }

以下是PHP文件的奖励:

<?php 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['files'])) {
        $errors = [];
        $path = 'uploads/';
        $extensions = ['jpg', 'jpeg', 'png', 'gif'];

        $all_files = count($_FILES['files']['tmp_name']);  
            $file_tmp = $_FILES['files']['tmp_name'][0];
            $file_type = $_FILES['files']['type'][0];
            $file_size = $_FILES['files']['size'][0];
            $file_ext = strtolower(end(explode('.', $_FILES['files']['name'][0])));
            $file_name = uniqid().".".$file_ext;
            $file = $path . $file_name;
            if (empty($errors)) {
                move_uploaded_file($file_tmp, $file);
            }
        if ($errors) print_r($errors);
    }
}