In IONIC 3, How do I upload a file such as a word or pdf on ios ?

5.5k views Asked by At

I am not sure where to start, I have used the phonegap filechooser, but not sure how to read the file and send its contents afterwords to the server

1

There are 1 answers

2
Sampath On

You can easily use File Transfer and File native plugins for your task.

Extracted from the official doc:

ionic cordova plugin add cordova-plugin-file-transfer

npm install --save @ionic-native/file-transfer

ionic cordova plugin add cordova-plugin-file

npm install --save @ionic-native/file

.ts

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

constructor(private transfer: FileTransfer, private file: File) { }


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

// Upload a file:
fileTransfer.upload(..).then(..).catch(..);

// Download a file:
fileTransfer.download(..).then(..).catch(..);

// Abort active transfer:
fileTransfer.abort();

// full example
upload() {
  let options: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}
   }

  fileTransfer.upload('<file path>', '<api endpoint>', options)
   .then((data) => {
     // success
   }, (err) => {
     // error
   })
}

download() {
  const url = 'http://www.example.com/file.pdf';
  fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
    console.log('download complete: ' + entry.toURL());
  }, (error) => {
    // handle error
  });
}