Need help upgrading to Ionic Framework 4.0? Get assistance with our Enterprise Migration Services EXPLORE NOW

File Transfer

Improve this doc

This plugin allows you to upload and download files.

Repo: https://github.com/apache/cordova-plugin-file-transfer

Installation

  1. Install the Cordova and Ionic Native plugins:
    $ ionic cordova plugin add cordova-plugin-file-transfer
    $ npm install --save @ionic-native/file-transfer@4
    
  2. Add this plugin to your app's module

Supported platforms

Usage

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
  });
}

To store files in a different/publicly accessible directory, please refer to the following link https://github.com/apache/cordova-plugin-file#where-to-store-files

Instance Members

FileTransferErrorCode

Error code rejected from upload with FileTransferError Defined in FileTransferError. FILE_NOT_FOUND_ERR: 1 Return when file was not found INVALID_URL_ERR: 2, Return when url was invalid CONNECTION_ERR: 3, Return on connection error ABORT_ERR: 4, Return on aborting NOT_MODIFIED_ERR: 5 Return on ‘304 Not Modified’ HTTP response

create()

Creates a new FileTransfer object

Returns: FileTransferObject

FileTransferObject

Instance Members

upload(fileUrl, url, options, trustAllHosts)

Sends a file to a server.

Param Type Details
fileUrl string

Filesystem URL representing the file on the device or a data URI. For backwards compatibility, this can also be the full path of the file on the device.

url string

URL of the server to receive the file, as encoded by encodeURI().

options FileUploadOptions

Optional parameters.

trustAllHosts boolean

Optional parameter, defaults to false. If set to true, it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS.

Returns: Promise<FileUploadResult> Returns a Promise that resolves to a FileUploadResult and rejects with FileTransferError.

download(source, target, trustAllHosts, Optional)

Downloads a file from server.

Param Type Details
source string

URL of the server to download the file, as encoded by encodeURI().

target string

Filesystem url representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device.

trustAllHosts boolean

Optional parameter, defaults to false. If set to true, it accepts all security certificates. This is useful because Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS.

Optional object

parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).

Returns: Promise<any> Returns a Promise that resolves to a FileEntry object.

onProgress(listener)

Registers a listener that gets called whenever a new chunk of data is transferred.

Param Type Details
listener Function

Listener that takes a progress event.

abort()

Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.

FileUploadOptions

Param Type Details
fileKey string

The name of the form element. Defaults to 'file'.

(optional)
fileName string

The file name to use when saving the file on the server. Defaults to 'image.jpg'.

(optional)
httpMethod string

The HTTP method to use - either PUT or POST. Defaults to POST.

(optional)
mimeType string

The mime type of the data to upload. Defaults to image/jpeg.

(optional)
params { [s: string]: any }

A set of optional key/value pairs to pass in the HTTP request.

(optional)
chunkedMode boolean

Whether to upload the data in chunked streaming mode. Defaults to true.

(optional)
headers { [s: string]: any }

A map of header name/header values. Use an array to specify more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used.

(optional)

FileUploadResult

Param Type Details
bytesSent number

The number of bytes sent to the server as part of the upload.

responseCode number

The HTTP response code returned by the server.

response string

The HTTP response returned by the server.

headers { [s: string]: any }

The HTTP response headers by the server.

FileTransferError

Param Type Details
code number

One of the predefined error codes listed below.

source string

URL to the source.

target string

URL to the target.

http_status number

HTTP status code. This attribute is only available when a response code is received from the HTTP connection.

body string

Response body. This attribute is only available when a response is received from the HTTP connection.

exception string

Either e.getMessage or e.toString.

API

Native

General