Upload File (pdf, docx, xlsx, ppt, etc) ke Server Ionic 3 - Mari Belajar Coding

15 September 2019

Upload File (pdf, docx, xlsx, ppt, etc) ke Server Ionic 3

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

Selamat datang di blog mari belajar coding. Tutorial kali ini kita akan belajar membuat aplikasi mobile untuk upload file ber ekstensi .pdf, .docx, .xlsx, .ppt, .png, .jpg dan lainnya ke server dengan framework Ionic dan PHP sebagai web servernya. 

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

Pertama-tama kita create app baru dengan Ionic dengan nama aplikasi uploadfile. Tambahkan --type=-ionic-angular untuk membuat aplikasi Ionic 3 dan --cordova untuk integerasi dengan cordova. 
ionic start uploadfile blank --type=ionic-angular --cordova

Selanjutnya instal plugin yang di perlukan untuk membuat aplikasi upload file ke server Ionic 3.
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

Setelah semua plugin diinstal, tambahkan import module plugin di app.module.ts.
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 {}

Buat button choose file dan Upload di file home.html.
<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>

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

Buat fungsi choose file dan upload di home.ts seperti dibawah ini.
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();
  }

}

Keterangan:
alamat url di atas merupakan alamat web service untuk menangani proses upload file disisi server. Url http://10.0.2.2 merupakan url localhost PC jika aplikasi mobile yang kita buat di jalankan menggunakan emulator android studio. Atau teman-teman bisa menggunakan alamat IP private PC jika menggunakan real device seperti contoh diatas.  Pastikan PC dan  real device dalam satu jaringan.

Tambahkan include subdomains IP PC kita  di file network_security_config.xml yang berada pada folder resources/android/xml untuk menghindari Cleartext Traffic Error saat upload file. Silahkan sesuaikan dengan IP PC teman-teman.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">192.168.99.187</domain>
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

Terakhir buat service di sisi server dengan PHP untuk menangani proses upload file. Buat folder bernama upload-file-ionic di  directory xampp/htdocs. Buat file bernama upload.php seperti dibawah ini.
<?php
header('Access-Control-Allow-Origin: *');

$tempdir = "uploads/"; 
if (!file_exists($tempdir))
mkdir($tempdir,0755);
$target_path = $tempdir;   


$newfilename = round(microtime(true)) . '-' . basename( $_FILES['file']['name']);

$target_path = $target_path . $newfilename;
 
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    echo "Upload and move success";
} else {
echo $target_path;
    echo "There was an error uploading the file, please try again!";
}
?>

Jalankan aplikasi dengan mengetikkan ionic run android di CMD atau terminal.

Tutorial membuat aplikasi upload file ke server dengan Ionic 3 telah selesai. Sekian.

Related Posts

Load comments