Skip to content

Latest commit

 

History

History
93 lines (77 loc) · 2.77 KB

File metadata and controls

93 lines (77 loc) · 2.77 KB
Logo

@capacitor/file-transfer

The FileTransfer API provides mechanisms for downloading and uploading files.
🔌 Cordova Plugin · 🤖 Android Library · 🍏 iOS Library

🐛 Report Bug · 💡 Request Feature

Install

npm install @capacitor/file-transfer@latest-7
npx cap sync

Example

Download

import { FileTransfer } from '@capacitor/file-transfer';
import { Filesystem, Directory } from '@capacitor/filesystem';

// First get the full file path using Filesystem
const fileInfo = await Filesystem.getUri({
  directory: Directory.Data,
  path: 'downloaded-file.pdf'
});

try {
    // Then use the FileTransfer plugin to download
    await FileTransfer.downloadFile({
        url: 'https://example.com/file.pdf',
        path: fileInfo.uri,
        progress: true
    });
} catch(error) {
    // handle error - see `FileTransferError` interface for what error information is returned
}

// Progress events
FileTransfer.addListener('progress', (progress) => {
  console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`);
});

Upload

import { FileTransfer } from '@capacitor/file-transfer';
import { Filesystem, Directory } from '@capacitor/filesystem';

// First get the full file path using Filesystem
const fileInfo = await Filesystem.getUri({
  directory: Directory.Cache,
  path: 'image_upload.png'
});

try {
    // Then use the FileTransfer plugin to upload
    const result = await FileTransfer.downloadFile({
        url: 'https://example.com/upload_api',
        path: fileInfo.uri,
        chunkedMode: true,
        headers: {
            // Upload uses `multipart/form-data` by default.
            // If you want to avoid that, you can set the 'Content-Type' header explicitly.
            'Content-Type': 'application/octet-stream',
        },
        progress: false
    });
    // get server response and other info from result - see `UploadFileResult` interface
} catch(error) {
    // handle error - see `FileTransferError` interface for what error information is returned
}

Documentation

Refer to this page.