How to Upload File on Ionic 3 using Native File Transfer Plugin

by Didin J. on Aug 23, 2017 How to Upload File on Ionic 3 using Native File Transfer Plugin

Step by step tutorial on how to upload file to server on Ionic 3 and Cordova using Ionic Native File Transfer plugin.

This tutorial shows you how to upload the file to the server on Ionic 3 and Cordova using Ionic native file transfer plugin. It can store any files type to the server depends on file types that allowed by the server, but this time we will use an image file that taken from camera or document folder of the device. So, we will use another Ionic 3 native plugin that is Camera plugin. In our experience of storing file that uploaded from Mobile Apps save in server path, save in database table as a base64 string or outside of server for example to Amazon AWS S3. The location of the uploaded file save is handled by server or web server, in this tutorial we did not cover that. So, we are using our own Grails 3 application as the file server for this tutorial. The image file that uploaded will save inside the images folder of the root server URL.


Shortcut to the steps:


Ionic File Upload is one of the essential features in mobile apps development. Almost mobile apps have a feature of upload image, avatar, document, etc. In this tutorial, we will have a combination of Ionic Cordova File Transfer, Image Picker from the Camera or Library, and other required modules.

You can also learn and try these related tutorials:

Because we just show you on how to upload the file from mobile apps, that's mean the file uploaded from Android or iOS apps. That's why we're using the native file transfer plugin. The following tools and requirements should prepare before starting the tutorial.

After Node.js installed and able to run on Terminal or Node command line, run this command on the terminal or Node command line.

sudo npm install -g ionic cordova

On MS-Windows Node command line 'sudo' is not necessary. That command will install latest Ionic 3, Ionic CLI and Cordova.


Create New Ionic 3 and Cordova App

Still, on the terminal or Node command line, type this command to create new blank Ionic 3 and Cordova app.

ionic start ionic-file-upload blank

It will take a few minutes because it also runs 'npm install'. As you can see on the last line of the terminal, go to the newly created project folder.

cd ionic-file-upload

As usual, to make sure that Ionic 3 app working properly, run the app by type this command.

ionic serve --lab

It will automatically open the default browser and show Ionic app page.

How to Upload File on Ionic 3 using Native File Transfer Plugin - Ionic Serve Lab


Install and Configure Camera, File and File Transfer Plugin

What we need in our Ionic 3 and Cordova apps is the function to browse or take image file then send or upload the file to the server. To achieve that we use the combination of Camera, File and File Transfer plugin. All of that plugin is Ionic Native plugins. To install the plugins type the following commands.

ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera
ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file
ionic cordova plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/file-transfer

Open and edit 'src/app/app.module.ts' then add this import.

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { Camera } from '@ionic-native/camera';

Add those imported class into '@NgModule' providers.

providers: [
  StatusBar,
  SplashScreen,
  {provide: ErrorHandler, useClass: IonicErrorHandler},
  FileTransfer,
  FileUploadOptions,
  FileTransferObject,
  File,
  Camera
]

Now, the File and File Transfer plugin is ready to use the Ionic 3 app.


Create Upload Page and Controller

Next, we will use the existing generated page 'src/pages/home/home.html' and 'src/pages/home/home.ts' for uploading the image file. First, open and edit 'src/pages/home/home.html' then replace '<ion-content>' contents with this.

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

Which a button that triggers Image picker, an image preview, and a button that trigger Ionic image upload. Second, open and edit 'src/pages/home/home.ts' then add these imports of Ionic Angular LoadingController, ToastController, Native FileTransfer, FileUploadOptions, FileTransferObject (@ionic-native/file-transfer), Camera, and CameraOptions (@ionic-native/camera).

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

Add variable before constructor for holding image URI.

imageURI:any;
imageFileName:any;

Inject all plugin that imported to the controllers.

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

Add this function to get Image from Photo Library.

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://192.168.0.7:8080/api/uploadImage', 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);
  });
}

Also, add Toast Controller for display any error message.

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

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

  toast.present();
}

That's the small piece of codes use for getting and upload the image file.


Test Upload Image File using Android and iOS Device

You can use our Grails 3 uploader app or your own backend for the test this app. Make sure your server or backend run and File Transfer URL point to your server.

Now, install or reinstall Android and iOS Cordova platforms by typing this command.

ionic cordova platform rm android
ionic cordova platform add android
ionic cordova platform rm ios
ionic cordova platform add ios

Next, we run the app on an Android device by typing this command.

ionic cordova run android

You will see this default page when the app starts on an Android device.

How to Upload File on Ionic 3 using Native File Transfer Plugin - Home Page Android

Click on Get Image button the select Image file in the gallery or document folder then click the upload button.

How to Upload File on Ionic 3 using Native File Transfer Plugin - Upload results

Next, we run the app on iOS simulator by typing this command.

ionic cordova run ios

Do the same thing as Android on the app.

That it's, If you need the source code, you can find it on our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks

Loading…