Working example cordova FileTransfer plugin with Ionic 2 typescript

I was just wondering if anyone has found a way around the [quote=“dtaalbers, post:13, topic:47621”]
FileUploadOptions
[/quote] error. It seems if you are using visual studio to build app package and push to a device it wil choke o this erro. Which in turns stops the build process. In fact I have learned all typescript errors matter via visual studio even if ionic CLI will work pass it.

Hi, sorry for the late response. I guess you can try this to get rid of the typescript error. Just add it in the top of the class where you are using the FileUploadOptions.

declare var FileUploadOptions: any;
1 Like

Thanks, that worked.

For anyone that is interested. I’ve updated my example with the ionic-native wrapper. You can find the example here :slight_smile: .

I’m trying to make an application that will download from server(using Ionic 2, Typescript)
Mine is not working…
Can you give us an example of download?

Ill see what I can do when I have some time :slight_smile:

I have created a file transfer download example which you can find here. Instructions can be found inside the folder. I did some quick testing and everything seemed to be working. Let me know if you run in any troubles.

1 Like

after having read your source code I tried to implement it in a served and I get the following error:
XCEPTION: Error: Uncaught (in promise): ReferenceError: FileTransfer is not defined browser_adapter.js:77 EXCEPTION: Error: Uncaught (in promise): ReferenceError: FileTransfer is not definedBrowserDomAdapter.logError @ browser_adapter.js:77BrowserDomAdapter.logGroup @ browser_adapter.js:87ExceptionHandler.call @ exception_handler.js:57(anonymous function) @ application_ref.js:265schedulerFn @ async.js:123SafeSubscriber.__tryOrUnsub @ Subscriber.js:225SafeSubscriber.next @ Subscriber.js:174Subscriber._next @ Subscriber.js:124Subscriber.next @ Subscriber.js:88Subject._finalNext @ Subject.js:128Subject._next @ Subject.js:120Subject.next @ Subject.js:77EventEmitter.emit @ async.js:112NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ ng_zone.js:120NgZoneImpl.inner.inner.fork.onHandleError @ ng_zone_impl.js:66ZoneDelegate.handleError @ zone.js:327Zone.runGuarded @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @ zone.js:494 browser_adapter.js:77 STACKTRACE:BrowserDomAdapter.logError @ browser_adapter.js:77ExceptionHandler.call @ exception_handler.js:59(anonymous function) @ application_ref.js:265schedulerFn @ async.js:123SafeSubscriber.__tryOrUnsub @ Subscriber.js:225SafeSubscriber.next @ Subscriber.js:174Subscriber._next @ Subscriber.js:124Subscriber.next @ Subscriber.js:88Subject._finalNext @ Subject.js:128Subject._next @ Subject.js:120Subject.next @ Subject.js:77EventEmitter.emit @ async.js:112NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ ng_zone.js:120NgZoneImpl.inner.inner.fork.onHandleError @ ng_zone_impl.js:66ZoneDelegate.handleError @ zone.js:327Zone.runGuarded @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @ zone.js:494 browser_adapter.js:77 Error: Uncaught (in promise): ReferenceError: FileTransfer is not defined at resolvePromise (zone.js:538) at zone.js:574 at ZoneDelegate.invokeTask (zone.js:356) at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (ng_zone_impl.js:36) at ZoneDelegate.invokeTask (zone.js:355) at Zone.runTask (zone.js:256) at drainMicroTaskQueue (zone.js:474)BrowserDomAdapter.logError @ browser_adapter.js:77ExceptionHandler.call @ exception_handler.js:60(anonymous function) @ application_ref.js:265schedulerFn @ async.js:123SafeSubscriber.__tryOrUnsub @ Subscriber.js:225SafeSubscriber.next @ Subscriber.js:174Subscriber._next @ Subscriber.js:124Subscriber.next @ Subscriber.js:88Subject._finalNext @ Subject.js:128Subject._next @ Subject.js:120Subject.next @ Subject.js:77EventEmitter.emit @ async.js:112NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ ng_zone.js:120NgZoneImpl.inner.inner.fork.onHandleError @ ng_zone_impl.js:66ZoneDelegate.handleError @ zone.js:327Zone.runGuarded @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @ zone.js:494 zone.js:461 Unhandled Promise rejection: FileTransfer is not defined ; Zone: angular ; Task: Promise.then ; Value: ReferenceError: FileTransfer is not defined(…)consoleError @ zone.js:461_loop_1 @ zone.js:490drainMicroTaskQueue @ zone.js:494 zone.js:463 Error: Uncaught (in promise): ReferenceError: FileTransfer is not defined(…)
Here are the source of my service:

import{Storage,SqlStorage} from ‘ionic-angular’;
import {Injectable} from ‘@angular/core’;
import {Transfer} from ‘ionic-native’;
@Injectable()
export class ServiceFavoris{
constructor(){

}
add(favoris){ 
    favoris.src.forEach(function(element) {
        stringReq = 'INSERT INTO Favoris (vid,src) VALUES ("'+favoris.id+'","'+element+'")';
        const ft = new Transfer();
        let targetPath = `${cordova.file.applicationDirectory}www/cache/img/`+element;
         ft.download(element, targetPath).then(() => {
            this.savedTo = targetPath;
            this.showImage = true;
        });
    }, this);
}
get(){
}

}

You cant expect it work when you ionic serve it because you are using cordova plugins. Cordova plugins only work when you deploy to a device or emulator.

Have you read the README I provided? :slight_smile: You can find it here.

So in short

  • You need to have the plugins installed ionic plugins add cordova-plugin-file & ionic plugins add cordova-plugin-filetransfer
  • Make sure you deployed to a device or emulator.

I realized I was doing since its ionic serve must be for his thanks.

Wow thank you so much. I’ll let you know when i run the code on the device. Currently I have no available actual device.

I solved it the following easy way. I hope this helps everyone. Kindly design your api to accept multipart/form-data with the “fileKey” value and upload as follows :-

// WORKS ONLY FOR ANDROID

findProfilePic(){
    // Get Path from FileChooser
    FileChooser.open()
      .then(
        uri => {    
        // Resolve Native Path .. ///storage/sdcard0/DCIM etc..                 
        FilePath.resolveNativePath(uri)
        .then(filePath => {                 
          this.profilePicUpload(filePath); //Pass value to Upload Handler
        });
      });
  }
  
  profilePicUpload(x){
      let fileTransfer = new Transfer();     
      //Upload Options
      this.options = {
        fileKey: 'pic',
        fileName: x,
        mimeType: "multipart/form-data",
        params: {
          name: x,
        }
      }
      // Upload to API
      fileTransfer.upload(x, encodeURI("YOUR_API_URL_HERE"), this.options, true)
      .then((data) => {
        let alert = this.alertCtrl.create({
              title: 'Message',
              subTitle: "Success",
              buttons: ['Dismiss'],
            });
            alert.present();
      }, (err) => {
        let alert = this.alertCtrl.create({
              title: err.text(),
              subTitle: err.json(),
              buttons: ['Dismiss'],
            });
            alert.present();
      });
    }

Kindly check on device and get back to me. Hope this helps someone as I struggled a lot. Dont forget to add the following line as well

import { FileChooser, Transfer, FilePath } from 'ionic-native';

1 Like

How to i upload my file?
I want to Upload my file (image ,PDF )
How to i do this ?

Hi, in the project I posted you will find a working example (most of the code relevant to you will be in home.ts)

hi @periyasamy17 , Please visit the link, to learn about the file uploading.

I updated my example app, you can find it here :slight_smile:

Other possibility I am using
Base64 encoding and simple http post with content and destination filetype.
However you have to know that base64 encoded file is 4/3 bigger than original.

can you list down the plugins you used in this example.

@dtaalbers sir i have tried to upload image using file transfer plugin image is uploaded but not stored in API backend.i have sent the data in Backend using formdata.sir image is uploaded bit not stored in backend.sir check below code:

[`
public uploadImage() {
// Destination URL
var url = “https://ams.consagous.co.in/auth/update_profile_image”;

// File for Upload
var targetPath = this.pathForImage(this.lastImage);
// File name only
var filename = this.lastImage;

//
var clientConfirmData = new FormData();
clientConfirmData.append(‘image’, filename);

var options = {
  fileKey: "file",
   chunkedMode: false,
  fileName: this.lastImage,
  mimeType: "multipart/form-data",
   headers: {'userid' :  this.userObject.user_id},
  params : clientConfirmData
};

const fileTransfer : FileTransferObject = this.transfer.create();

// Use the FileTransfer to upload the image
fileTransfer.upload(targetPath, url, options).then(data => {
let response = data.response;
var r = JSON.parse(response);

  if(r.status) { 
    this.selectedImage = r;
    this.userObject.image = r.image;
  } 

this.presentToast('Image succesful uploaded');

}, err => {
console.log(‘ddd’ +err);
this.presentToast(‘Error while uploading file.’);
});