Tuesday, October 8, 2019

Upload File (pdf, docx, xlsx, ppt, etc) to Serve Ionic 3



In this tutorial we will learn to create a mobile application for uploading files with extensions such as .pdf, .docx, .xlsx, .ppt, .png, .jpg and others to servers with the Ionic and PHP frameworks as the web server.

Upload File (pdf, docx, xlsx, ppt, etc) ke Serve Ionic 3
First we create a new app with Ionic with the name uploadfile application . Add --type = -ionicangular to create Ionic 3 and --cordova applications for integration with cordova.

ionic start uploadfile blank --type=ionic-angular --cordova  

First we create a new app with Ionic with the name
uploadfile application . Add --type = -ionicangular to create Ionic 3 and --cordova
applications for integration with cordova. application upload files to the Ionic 3 server.

ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file@4
ionic cordova plugin add cordova-plugin-filechooser
npm install --save @ionic-native/file-chooser@4
ionic cordova plugin add cordova-plugin-filepath
npm install --save @ionic-native/file-path@4
ionic cordova plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/file-transfer@4

After all plugins are installed, add the plugin module import in      

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { File } from '@ionic-native/file';
import { FileChooser } from '@ionic-native/file-chooser';
import { FilePath } from '@ionic-native/file-path';
import { FileTransfer } from '@ionic-native/file-transfer';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    File,
    FileChooser,
    FilePath,
    FileTransfer,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}


Create a button choose file and upload it at
home.html file

<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Mari Belajar Coding
    </ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <button ion-button color="light" (click)="ChooseFile()">Choose File</button>
  <p text-wrap>{{FileName}}</p>
  <button ion-button block color="primary" (click)="UploadFile()">Upload</button>
</ion-content>


Make the function choose file and upload it at home.ts as below. 

import { Component, NgZone  } from '@angular/core';
import { NavController,ToastController, LoadingController } from 'ionic-angular';
import { FileChooser } from '@ionic-native/file-chooser';
import { FilePath } from '@ionic-native/file-path';
import { File,FileEntry } from '@ionic-native/file';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  FileURI:any;
  FileName:any;
  constructor(public navCtrl: NavController,
    public toastCtrl: ToastController,
    public loadingCtrl: LoadingController,
    private fileChooser: FileChooser,
    private filePath: FilePath,
    private file: File,
    private transfer: FileTransfer,
    private zone: NgZone) {

  }

  ChooseFile(){
    //get file with cordova file chooser
    this.fileChooser.open()
      .then(uri => {
        //file uri for upload
        this.FileURI=uri;
        this.filePath.resolveNativePath(uri) //get file path
        .then(filePath => {
          this.file.resolveLocalFilesystemUrl(filePath).then(fileInfo => //get info file
            {
              let files = fileInfo as FileEntry;
              files.file(success =>
                { 
                  this.zone.run(() => { //updating binding file name
                    this.FileName=success.name; //get file name
                  }); 
                });
            },err =>
            {
              console.log(err);
              throw err;             
            });
        });
      }).catch(e => console.log(e));    
  }

  UploadFile() {
    //show loading spinner
    let loader = this.loadingCtrl.create({
      content: "Uploading..."
    });
    loader.present();

    const fileTransfer: FileTransferObject = this.transfer.create(); 
    //Local PC Web service if using an emulator
    let URL="http://10.0.2.2/upload-file-ionic/upload.php";

    //Local PC Web service if using the real device and in one network
    //let URL="http://192.168.99.187/upload-file-ionic/upload.php";
    
    //option upload
    let options: FileUploadOptions = {
      fileKey: 'file',
      fileName: this.FileName,
      chunkedMode: false,
     // params: {'UserID':'1234'}, // add another parameter (opsional)
      headers: {}
    } 
    fileTransfer.upload(this.FileURI, URL, options)
      .then((data) => {
      console.log(data);
      loader.dismiss();
      this.presentToast("File uploaded successfully");
    }, (err) => {
      console.log(err);
      loader.dismiss();
      this.presentToast("Error");
    });
  }

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

}




Advertiser