@capacitor/file-transfer

中文文档
2.0.6发布于 2026/10/03MITTypeScriptESM + CJS构建来源已验证近 30 天下载 45.1万

The FileTransfer API provides mechanisms for downloading and uploading files.

原始使用文档
文档目录11 节
  1. Install
  2. Example
  3. Download
  4. Upload
  5. API
  6. downloadFile(...)
  7. uploadFile(...)
  8. addListener('progress', ...)
  9. removeAllListeners()
  10. Interfaces
  11. Errors

@capacitor/file-transfer

The FileTransfer API provides mechanisms for downloading and uploading files.

Install

npm install @capacitor/file-transfer
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) {
    if (error.code === 'OS-PLUG-FLTR-0010') {
      // HTTP error - see `FileTransferError` for details on fields available in `errorData`
      let errorData = error.data;
      this.showError('Upload failed: ' + errorData.httpStatus + '; ' + errorData.body);
    } else {
      // other errors - use `error.code` and `error.message` for more information.
      this.showError('Upload failed: ' + error.code + '; ' + error.message);
    }
}

// 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.uploadFile({
        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) {
    if (error.code === 'OS-PLUG-FLTR-0010') {
      // HTTP error - see `FileTransferError` for details on fields available in `errorData`
      let errorData = error.data;
      this.showError('Upload failed: ' + errorData.httpStatus + '; ' + errorData.body);
    } else {
      // other errors - use `error.code` and `error.message` for more information.
      this.showError('Upload failed: ' + error.code + '; ' + error.message);
    }
}

API

Note: Some of the input options come from HttpOptions in @capacitor/core, but the plugin does not use all parameters from HttpOptions. The ones that are used are documented below.

For list of existing error codes, see Errors.

downloadFile(...)

downloadFile(options: DownloadFileOptions) => Promise<DownloadFileResult>

Perform an HTTP request to a server and download the file to the specified destination.

If the server returns an HTTP error (e.g. 404, 500, etc.), the promise will be rejected. To get information about the HTTP error response when running on Android and iOS (not applicable to web), use the FileTransferError interface available at error.data attribute.

ParamType
optionsDownloadFileOptions

Returns: Promise<DownloadFileResult>

Since: 1.0.0


uploadFile(...)

uploadFile(options: UploadFileOptions) => Promise<UploadFileResult>

Perform an HTTP request to upload a file to a server.

If the server returns an HTTP error (e.g. 404, 500, etc.), the promise will be rejected. To get information about the HTTP error response when running Android and iOS (not applicable to web), use the FileTransferError interface available at error.data attribute.

ParamType
optionsUploadFileOptions

Returns: Promise<UploadFileResult>

Since: 1.0.0


addListener('progress', ...)

addListener(eventName: "progress", listenerFunc: (progress: ProgressStatus) => void) => Promise<PluginListenerHandle>

Add a listener to file transfer (download or upload) progress events.

ParamType
eventName'progress'
listenerFunc(progress: ProgressStatus) => void

Returns: Promise<PluginListenerHandle>

Since: 1.0.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 1.0.0


Interfaces

DownloadFileResult

PropTypeDescriptionSince
pathstringThe path the file was downloaded to.1.0.0
blobBlobThe blob data of the downloaded file. This is only available on web.1.0.0

DownloadFileOptions

PropTypeDescriptionSince
urlstringThe URL to download the file from.1.0.0
pathstringThe full file path the downloaded file should be moved to. You may use a plugin like @capacitor/filesystem to get a complete file path.1.0.0
progressbooleanIf true, progress event will be dispatched on every chunk received. See addListener() for more information. Chunks are throttled to every 100ms on Android/iOS to avoid slowdowns. Default is false.1.0.0
methodstringThe Http Request method to run. (Default is GET)1.0.0
paramsHttpParamsURL parameters to append to the request. This HttpParams interface comes from @capacitor/core.1.0.0
headersHttpHeadersHttp Request headers to send with the request. This HttpHeaders interface comes from @capacitor/core.1.0.0
readTimeoutnumberHow long to wait to read additional data in milliseconds. Resets each time new data is received. Default is 60,000 milliseconds (1 minute). Not supported on web.1.0.0
connectTimeoutnumberHow long to wait for the initial connection in milliseconds. Default is 60,000 milliseconds (1 minute). In iOS, there's no real distinction between connectTimeoutand readTimeout. Plugin tries to use connectTimeout, if not uses readTimeout, if not uses default1.0.0
disableRedirectsbooleanSets whether automatic HTTP redirects should be disabled1.0.0
shouldEncodeUrlParamsbooleanUse this option if you need to keep the URL unencoded in certain cases (already encoded, azure/firebase testing, etc.). The default is true. Not supported on web.1.0.0

HttpParams

HttpHeaders

UploadFileResult

PropTypeDescriptionSince
bytesSentnumberTotal number of bytes uploaded1.0.0
responseCodestringHTTP response code for the upload1.0.0
responsestringHTTP response body from the upload (when available)1.0.0
headers{ [key: string]: string; }HTTP headers from the upload response (when available)1.0.0

UploadFileOptions

PropTypeDescriptionSince
urlstringThe URL to upload the file to.1.0.0
pathstringFull file path of the file to upload. You may use a plugin like @capacitor/filesystem to get a complete file path.1.0.0
blobBlobBlob data to upload. Will use this instead of path if provided. This is only available on web.1.0.0
chunkedModebooleanWhether to upload data in a chunked streaming mode. Not supported on web. Note: The upload uses Content-Type: multipart/form-data, when chunkedMode is true. Depending on your backend server, this can cause the upload to fail. If your server expects a raw stream (e.g. application/octet-stream), you must explicitly set the Content-Type header in headers.1.0.0
mimeTypestringMime type of the data to upload. Only used if "Content-Type" header was not provided.1.0.0
fileKeystringType of form element. The default is set to "file". Only used if "Content-Type" header was not provided.1.0.0
progressbooleanIf true, progress event will be dispatched on every chunk received. See addListener() for more information. Chunks are throttled to every 100ms on Android/iOS to avoid slowdowns. Default is false.1.0.0
methodstringThe Http Request method to run. (Default is POST)1.0.0
paramsHttpParamsURL parameters to append to the request. This HttpParams interface comes from @capacitor/core.1.0.0
headersHttpHeadersHttp Request headers to send with the request. This HttpHeaders interface comes from @capacitor/core.1.0.0
readTimeoutnumberHow long to wait to read additional data in milliseconds. Resets each time new data is received. Default is 60,000 milliseconds (1 minute). Not supported on web.1.0.0
connectTimeoutnumberHow long to wait for the initial connection in milliseconds. Default is 60,000 milliseconds (1 minute). Not supported on web. In iOS, there's no real distinction between connectTimeoutand readTimeout. Plugin tries to use connectTimeout, if not uses readTimeout, if not uses default1.0.0
disableRedirectsbooleanSets whether automatic HTTP redirects should be disabled. Not supported on web.1.0.0
shouldEncodeUrlParamsbooleanUse this option if you need to keep the URL unencoded in certain cases (already encoded, azure/firebase testing, etc.). The default is true. Not supported on web.1.0.0

PluginListenerHandle

PropType
remove() => Promise<void>

ProgressStatus

PropTypeDescriptionSince
type'download' | 'upload'The type of transfer operation (download or upload).1.0.0
urlstringThe url of the file associated with the transfer (download or upload).1.0.0
bytesnumberThe number of bytes transferred so far.1.0.0
contentLengthnumberThe total number of bytes associated with the file transfer.1.0.0
lengthComputablebooleanWhether or not the contentLength value is relevant. In some situations, the total number of bytes may not be possible to determine.1.0.0

FileTransferError

PropTypeDescriptionSince
codestringCode identifying the error: OS-PLUG-FLTR-XXXX1.0.0
messagestringMessage informing of what went wrong1.0.0
sourcestringThe source for the file transfer operation (a url for download, a file path for upload)1.0.0
targetstringThe target of the file transfer operation (a file path for download, a url for upload)1.0.0
httpStatusnumberHTTP status code of the server response (if available)1.0.0
headers{ [key: string]: string; }HTTP headers from the server response (if available)1.0.0
bodystringHTTP error response body from the server (if available)1.0.0
exceptionstringException message thrown on native side (if available)1.0.0

Errors

The plugin returns the following errors with specific codes on iOS, Android, and Web:

Error codePlatform(s)Description
OS-PLUG-FLTR-0004Android, iOSThe method's input parameters aren't valid.
OS-PLUG-FLTR-0005Android, iOSInvalid server URL was provided or URL is empty.
OS-PLUG-FLTR-0006Android, iOSUnable to perform operation, user denied permission request.
OS-PLUG-FLTR-0007Android, iOSOperation failed because file does not exist.
OS-PLUG-FLTR-0008Android, iOS, WebFailed to connect to server.
OS-PLUG-FLTR-0009Android, iOSThe server responded with HTTP 304 – Not Modified. If you want to avoid this, check your headers related to HTTP caching.
OS-PLUG-FLTR-0010Android, iOSThe server responded with an HTTP error status code.
OS-PLUG-FLTR-0011Android, iOS, WebThe operation failed with an error (generic error).

When handling errors in your application, you can check the error code to determine the specific issue. The error object typically contains additional information such as:

  • code: The error code (as shown in the table above)
  • message: A human-readable description of the error
  • source: The source of the transfer (file path or URL)
  • target: The target of the transfer (file path or URL)
  • httpStatus: The HTTP status code (for HTTP errors)
  • body: The response body (for HTTP errors)
  • headers: The response headers (for HTTP errors)

版本与发布记录

@capacitor/file-transfer 共发布 26 个版本,首次发布于 2025/05/27;过去 12 个月发布了 16 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.6latest2026/10/031 个月前
3.0.0-alpha.0next2026/08/122 个月前
2.0.52026/08/122 个月前
1.0.12latest-72026/03/127 个月前
1.0.112026/02/128 个月前
1.0.102026/02/118 个月前

其他发布通道:dev → 1.0.0-dev.1,latest-7 → 1.0.12,next → 3.0.0-alpha.0。

关于 @capacitor/file-transfer 的常见问题

@capacitor/file-transfer 是什么?

The FileTransfer API provides mechanisms for downloading and uploading files.

如何安装 @capacitor/file-transfer?

在项目目录运行 npm install @capacitor/file-transfer,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capacitor/file-transfer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capacitor/file-transfer 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capacitor/file-transfer 可以商用吗?

@capacitor/file-transfer 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@capacitor/file-transfer 的下载量有多少?

根据 npm 官方下载统计,@capacitor/file-transfer 在 2026/10/09 – 2026/11/07 这 30 天内被下载 450,676 次,日均约 15,023 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capacitor/file-transfer 还在维护吗?

最新版本 2.0.6 发布于 2026/10/03(1 个月前);至今共发布 26 个版本,其中过去 12 个月发布了 16 个;首次发布于 2025/05/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。