# @capacitor/file-transfer 中文文档

规范地址：https://npmcn.com/package/%40capacitor/file-transfer/

版本：2\.0\.6
npm 元数据更新时间：2026-10-02T16:51:36.846Z
中文译文更新时间：2026-11-09T01:54:17.609Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40capacitor/file-transfer
原文对照：https://npmcn.com/package/%40capacitor/file-transfer/?lang=original
项目主页：https://github.com/ionic-team/capacitor-file-transfer#readme
源码仓库：https://github.com/ionic-team/capacitor-file-transfer

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：106 kB，21 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@capacitor/core \>=8\.0\.0
- 首次发布：2025-05-27T10:14:17.582Z
- 最新版本发布：2026-10-02T16:51:36.384Z
- 近 30 天下载量：450676（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：26（近 12 个月 16 个）

## 中文简介

File Transfer API提供了下载和上传文件的机制.

## 安装

```sh
npm install @capacitor/file-transfer
```

也可以使用：`pnpm add @capacitor/file-transfer`、`yarn add @capacitor/file-transfer`、`bun add @capacitor/file-transfer`

## README

# @ concessor/ file- transfer

File Transfer API提供了下载和上传文件的机制.

## 安装

```bash
npm install @capacitor/file-transfer
npx cap sync
```

## 示例

### 下载

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

### 上传

```typescript
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 密码

-   [`downloadFile(...)`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-downloadfile)
-   [`uploadFile(...)`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-uploadfile)
-   [`addListener('progress', ...)`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-addlistenerprogress-)
-   [`removeAllListeners()`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-removealllisteners)
-   [接口](https://npmcn.com/package/%40capacitor/file-transfer/#readme-interfaces)

注:一些输入选项来自 `HttpOptions` 内 `@capacitor/core`,但插件没有使用来自 `HttpOptions`兹将所使用的标准说明如下.

现有错误代码列表参见 [错误](https://npmcn.com/package/%40capacitor/file-transfer/#readme-errors)。 。 。 .

### 下载文件(...)

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

向服务器执行 HTTP 请求,并将文件下载到指定的目的地 .

如果服务器返回 HTTP 错误( 如 404, 500等), 则承诺会被拒绝 . 要获得Android和iOS运行时HTTP错误响应的信息(不适用于网络),请使用 [`FileTransferError`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-filetransfererror) 接口可用 `error.data` 属性.

| 参数 | 类型 |
| --- | --- |
| **`options`** | `[DownloadFileOptions](https://npmcn.com/package/%40capacitor/file-transfer/#readme-downloadfileoptions)` |

**回返情况:** `Promise<[DownloadFileResult](https://npmcn.com/package/%40capacitor/file-transfer/#readme-downloadfileresult)>`

**自:** 1.0.0 (单位:千美元)

* * *

### 上传文件(...)

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

执行 HTTP 上传文件到服务器的请求 .

如果服务器返回 HTTP 错误( 如 404, 500等), 则承诺会被拒绝 . 要获得运行Android和iOS(不适用于网络)时HTTP错误响应的信息,请使用 [`FileTransferError`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-filetransfererror) 接口可用 `error.data` 属性.

| 参数 | 类型 |
| --- | --- |
| **`options`** | `[UploadFileOptions](https://npmcn.com/package/%40capacitor/file-transfer/#readme-uploadfileoptions)` |

**回返情况:** `Promise<[UploadFileResult](https://npmcn.com/package/%40capacitor/file-transfer/#readme-uploadfileresult)>`

**自:** 1.0.0 (单位:千美元)

* * *

### 添加倾听器( “ 进度 ” ,...)

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

在文件传输(下載或上傳)进度事件上添加一个收听器.

| 参数 | 类型 |
| --- | --- |
| **`eventName`** | `'progress'` |
| **`listenerFunc`** | `(progress: [ProgressStatus](https://npmcn.com/package/%40capacitor/file-transfer/#readme-progressstatus)) => void` |

**回返情况:** `Promise<[PluginListenerHandle](https://npmcn.com/package/%40capacitor/file-transfer/#readme-pluginlistenerhandle)>`

**自:** 1.0.0 (单位:千美元)

* * *

### 删除所有收听器( )

```typescript
removeAllListeners() => Promise<void>
```

删除此插件的所有听众 .

**自:** 1.0.0 (单位:千美元)

* * *

### 接口

#### 下载文件

| Prop | 类型 | 说明 | 自兹 |
| --- | --- | --- | --- |
| **`path`** | `string` | 文件下载到的路径 . | 1.0.0 (单位:千美元) |
| **`blob`** | `Blob` | 下载文件的 blob 数据 。 这只在网上提供. | 1.0.0 (单位:千美元) |

#### 下载文件选项

| Prop | 类型 | 说明 | 自兹 |
| --- | --- | --- | --- |
| **`url`** | `string` | 要下载文件的 URL . | 1.0.0 (单位:千美元) |
| **`path`** | `string` | 下载文件的完整文件路径应该移动到 。 您可以使用这样的插件 `@capacitor/filesystem` 要获得完整的文件路径. | 1.0.0 (单位:千美元) |
| **`progress`** | `boolean` | 如果是真的, 将会在收到的每个块上发出进度事件 。 更多信息请见添加倾听者( ) 。 在Android/iOS上,春克被压到每100米,以避免减速. 默认是 `false`。 。 。 . | 1.0.0 (单位:千美元) |
| **`method`** | `string` | Http 请求方法运行 。 (过失是得到) | 1.0.0 (单位:千美元) |
| **`params`** | `[HttpParams](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpparams)` | 请求附加的 URL 参数 。 这个 [`HttpParams`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpparams) 界面来自 `@capacitor/core`。 。 。 . | 1.0.0 (单位:千美元) |
| **`headers`** | `[HttpHeaders](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpheaders)` | Http 请求头随请求一起发送. 这个 [`HttpHeaders`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpheaders) 界面来自 `@capacitor/core`。 。 。 . | 1.0.0 (单位:千美元) |
| **`readTimeout`** | `number` | 需要等多久才能读取以毫秒计的额外数据. 每次收到新数据时都会重新设置 。 默认为6万毫秒(1分). 不在网络上支持 . | 1.0.0 (单位:千美元) |
| **`connectTimeout`** | `number` | 在毫秒内等待初始连接需要多长时间. 默认为6万毫秒(1分). 在iOS中,没有真正的区分 `connectTimeout`财务报告和审定财务报表 `readTimeout`。试图使用的插件 `connectTimeout`,如果没有使用 `readTimeout`,如果不使用默认值 | 1.0.0 (单位:千美元) |
| **`disableRedirects`** | `boolean` | 设定是否禁用 HTTP 自动方向 | 1.0.0 (单位:千美元) |
| **`shouldEncodeUrlParams`** | `boolean` | 如果您在某些情况下需要保留未编码的 URL( 已经编码、 azure/ firebase 测试等) , 请使用此选项 。 默认是 `true`。在网络上不支持. | 1.0.0 (单位:千美元) |

#### 图片

#### Http 信头

#### 上传文件

| Prop | 类型 | 说明 | 自兹 |
| --- | --- | --- | --- |
| **`bytesSent`** | `number` | 上传的字节总数 | 1.0.0 (单位:千美元) |
| **`responseCode`** | `string` | 上传的 HTTP 响应代码 | 1.0.0 (单位:千美元) |
| **`response`** | `string` | 上传的 HTTP 响应正文( 当可用时) | 1.0.0 (单位:千美元) |
| **`headers`** | `{ [key: string]: string; }` | 上传回复中的 HTTP 信头( 可用时) | 1.0.0 (单位:千美元) |

#### 上传文件选项

| Prop | 类型 | 说明 | 自兹 |
| --- | --- | --- | --- |
| **`url`** | `string` | 要上传文件的 URL . | 1.0.0 (单位:千美元) |
| **`path`** | `string` | 要上传的文件的全部文件路径 。 您可以使用这样的插件 `@capacitor/filesystem` 要获得完整的文件路径. | 1.0.0 (单位:千美元) |
| **`blob`** | `Blob` | 要上传的 Blob 数据 。 如果提供路径, 将会使用此路径 。 这只在网上提供. | 1.0.0 (单位:千美元) |
| **`chunkedMode`** | `boolean` | 是否以块流模式上传数据 。 不在网络上支持 。 注意: 上传用途 `Content-Type: multipart/form-data`,当 `chunkedMode` 实值 `true`。这取决于您的后端服务器,可能导致上传失败。 如果您的服务器期望有一个生流( 例如 ) . `application/octet-stream`),您必须明确设置 `Content-Type` 页眉在 `headers`。 。 。 . | 1.0.0 (单位:千美元) |
| **`mimeType`** | `string` | 要上传的数据的MIME类型. 仅在未提供"Content-Type"标题的情况下使用. | 1.0.0 (单位:千美元) |
| **`fileKey`** | `string` | 形式元素的类型. 默认设置为"文件". 仅在未提供"Content-Type"标题的情况下使用. | 1.0.0 (单位:千美元) |
| **`progress`** | `boolean` | 如果是真的, 将会在收到的每个块上发出进度事件 。 更多信息请见添加倾听者( ) 。 在Android/iOS上,春克被压到每100米,以避免减速. 默认是 `false`。 。 。 . | 1.0.0 (单位:千美元) |
| **`method`** | `string` | Http 请求方法运行 。 (过失是 POST) | 1.0.0 (单位:千美元) |
| **`params`** | `[HttpParams](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpparams)` | 请求附加的 URL 参数 。 这个 [`HttpParams`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpparams) 界面来自 `@capacitor/core`。 。 。 . | 1.0.0 (单位:千美元) |
| **`headers`** | `[HttpHeaders](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpheaders)` | Http 请求头随请求一起发送. 这个 [`HttpHeaders`](https://npmcn.com/package/%40capacitor/file-transfer/#readme-httpheaders) 界面来自 `@capacitor/core`。 。 。 . | 1.0.0 (单位:千美元) |
| **`readTimeout`** | `number` | 需要等多久才能读取以毫秒计的额外数据. 每次收到新数据时都会重新设置 。 默认为6万毫秒(1分). 不在网络上支持 . | 1.0.0 (单位:千美元) |
| **`connectTimeout`** | `number` | 在毫秒内等待初始连接需要多长时间. 默认为6万毫秒(1分). 不在网络上支持 。 在iOS中,没有真正的区分 `connectTimeout`财务报告和审定财务报表 `readTimeout`。试图使用的插件 `connectTimeout`,如果没有使用 `readTimeout`,如果不使用默认值 | 1.0.0 (单位:千美元) |
| **`disableRedirects`** | `boolean` | 设定是否应当禁用 HTTP 自动重定向 。 不在网络上支持 . | 1.0.0 (单位:千美元) |
| **`shouldEncodeUrlParams`** | `boolean` | 如果您在某些情况下需要保留未编码的 URL( 已经编码、 azure/ firebase 测试等) , 请使用此选项 。 默认是 `true`。在网络上不支持. | 1.0.0 (单位:千美元) |

#### 插件听筒

| Prop | 类型 |
| --- | --- |
| **`remove`** | `() => Promise<void>` |

#### 进展现状

| Prop | 类型 | 说明 | 自兹 |
| --- | --- | --- | --- |
| **`type`** | `'download' | 'upload'` | 传输操作的类型(下載或上傳). | 1.0.0 (单位:千美元) |
| **`url`** | `string` | 与传输相关的文件的url(下載或上傳). | 1.0.0 (单位:千美元) |
| **`bytes`** | `number` | 至今转移的字节数 . | 1.0.0 (单位:千美元) |
| **`contentLength`** | `number` | 与文件传输相关的字节总数 . | 1.0.0 (单位:千美元) |
| **`lengthComputable`** | `boolean` | 内容Length值是否相关. 在某些情况下,字节的总数可能无法确定. | 1.0.0 (单位:千美元) |

#### 文件传输错误

| Prop | 类型 | 说明 | 自兹 |
| --- | --- | --- | --- |
| **`code`** | `string` | 识别错误的代码: OS-PLUG-FLTR---- | 1.0.0 (单位:千美元) |
| **`message`** | `string` | 消息告知出错 | 1.0.0 (单位:千美元) |
| **`source`** | `string` | 文件传输操作的出处( URL 为下载, 为上传的文件路径) | 1.0.0 (单位:千美元) |
| **`target`** | `string` | 文件传输操作的目标(用于下载的文件路径,用于上传的url) | 1.0.0 (单位:千美元) |
| **`httpStatus`** | `number` | 服务器响应的 HTTP 状态代码( 如果可用) | 1.0.0 (单位:千美元) |
| **`headers`** | `{ [key: string]: string; }` | 来自服务器响应的 HTTP 信头( 如果可用) | 1.0.0 (单位:千美元) |
| **`body`** | `string` | 服务器的 HTTP 错误响应机构( 如果可用) | 1.0.0 (单位:千美元) |
| **`exception`** | `string` | 向本地侧丢出例外消息( 如果有) | 1.0.0 (单位:千美元) |

### 错误

插件返回以下带有iOS、Android和Web特定代码的错误:

| 错误代码 | 平台( S) | 说明 |
| --- | --- | --- |
| OS-PLUG-FLTR-0004号卫星 | Android, iOS (英语) | 该方法的输入参数无效. |
| OS-PLUG-FLTR-0005 (英语) | Android, iOS (英语) | 提供了无效的服务器 URL 或 URL 为空 . |
| OS-PLUG-FLTR-0006 (英语) | Android, iOS (英语) | 无法执行操作, 用户拒绝权限请求 . |
| OS-PLUG-FLTR-0007 (英语) | Android, iOS (英语) | 操作失败, 因为文件不存在 . |
| OS-PLUG-FLTR-0008 (英语) | Android, iOS, Web (英语) | 连接到服务器失败 . |
| OS-PLUG-FLTR-0009 (英语) | Android, iOS (英语) | 服务器响应了HTTP 304 – 没有修改. 如果您想要避免这种情况, 请检查您与 HTTP 缓存相关的信头 . |
| OS-PLUG-FLTR-0010 (英语) | Android, iOS (英语) | 服务器以HTTP错误状态代码响应. |
| OS-PLUG-FLTR-0011 (英语) | Android, iOS, Web (英语) | 操作以出错( generic error) 失败 . |

在处理应用程序中的错误时,您可以检查错误代码以确定具体的问题. 错误对象通常包含额外信息,例如:

-   `code`: 错误代码(如上表所示)
-   `message`: 对错误的可读描述
-   `source`: 传输源(文件路径或 URL)
-   `target`: 传输的目标(文件路径或 URL)
-   `httpStatus`: HTTP 状态代码(用于 HTTP 错误)
-   `body`: 响应正体(用于 HTTP 错误)
-   `headers`: 响应头 (用于 HTTP 错误)

## 常见问题

### @capacitor/file-transfer 是什么？

File Transfer API提供了下载和上传文件的机制\.

### 如何安装 @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 和提交记录判断。

