file upload using IONIC native

≯℡__Kan透↙ 提交于 2019-12-23 05:58:12

问题


Brief Explanation: I am trying to use ionic native from android, Problem is , in console it says [object Object] Uploaded Successfully, but nothing is uploaded on my server.

I checked network tab in browser, it is not even calling the upload url. Please check my code below.

below is my home.html code:

<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 code:

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();
  }

}

回答1:


This is the script the works for me!

in html

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

in ts file

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);
  }

Bonus here is the PHP file:

<?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);
    }
}



回答2:


This is because you are not using an Exact API call.

In the code : fileTransfer.upload(this.imageURI, 'http://example.com/upload2.php', options)

You have to use Api call which is pointing to your api endpoint.

Try to read more about api calls.

Instead of http://example.com/upload2.php Your call should be like http://example.com/upload2.php/api/uploadmyimage where in upload2.php you have defined the get or post method for an /api/uploadmyimage



来源:https://stackoverflow.com/questions/49274786/file-upload-using-ionic-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!