@capacitor-ohos/file-transfer
v2.0.0
Published
The FileTransfer API provides mechanisms for downloading and uploading files.
Readme
@capacitor/file-transfer
本项目基于 @capacitor/[email protected] 开发。
简介
@capacitor/file-transfer是capacitor生态系统中的核心插件,提供文件上传与下载功能,可实现进度监听、请求头自定义等能力,为跨平台应用开发提供设备差异化适配能力,兼容capacitor的Android、iOS等主流移动平台及浏览器环境,本文档只说明在OpenHarmony系统中的使用。
API提供完善的文件上传与下载功能,支持进度监听、请求参数自定义等核心能力,适配OpenHarmony系统的文件传输场景,调用便捷、适配性强。
支持平台
- OpenHarmony:5.0+
下载安装
通过命令行或手动引入即可快速安装插件,支持从npm仓库获取。
命令行安装(推荐)
安装hionic CLI:
npm install -g hionic以下两种方式中任选其一即可,无需重复操作:
npm安装:
# 安装插件
npm install @capacitor/file-transfer
# 同步插件
hionic synchionic CLI安装:
hionic plugin add @capacitor/file-transfer手动引入安装
根据插件源码中 plugin.xml 配置在项目中引入插件,步骤如下:
1. 添加插件配置
根据 plugin.xml 的 config-json 项,通过 target 字段找到 entry 模块中 capacitor.plugins.json 文件,并根据 param
标签添加配置如下:
{
"pkg": "@capacitor/file-transfer",
"classpath": "FileTransfer"
}2. 修改 CMake 配置
根据 plugin.xml 的 CMakeLists 项,通过 modules-name 字段找到模块 capacitor,路径为 target 字段的
CMakeLists.txt 文件,并添加 add_subdirectory 和 target_link_libraries 如下:
#START_ADD_SUBDIRECTORY
// ...
add_subdirectory(FileTransfer)
// ...
#END_ADD_SUBDIRECTORY
// ...
target_link_libraries(capacitor PUBLIC
// ...
"-Wl,--whole-archive"
// ...
FileTransfer
// ...
"-Wl,--no-whole-archive"
)3. 复制源码文件
根据 plugin.xml 的 source-file 项,根据 src 字段找到需要复制的文件,并根据 modules-name 字段和 target-dir
字段找到文件复制的具体模块和目录,具体操作如下:
将源码中src/main/cpp/FileTransfer目录下的FileTransfer.h、FileTransfer.cpp、CMakeLists.txt文件引入到capacitor模块中src/main/cpp/FileTransfer目录下。
将源码中src/main/ets/components/FileTransfer目录下的FileTransferAction.ets文件引入到capacitor模块中src/main/ets/components/FileTransfer目录下。
4. 添加 ArkTS 配置
在 capacitor 模块的 build-profile.json5 文件中,buildOption/arkOptions/runtimeOnly/sources
配置项数组中加入步骤3中拷贝的ets文件路径,具体配置如下:
{
"buildOption": {
// ...
"arkOptions": {
"runtimeOnly": {
"sources": [
// ...
"./src/main/ets/components/FileTransfer/FileTransferAction.ets"
// ...
]
}
}
}
}卸载
# 卸载 file-transfer 插件
hionic plugin remove @capacitor/file-transfer约束与限制
兼容性
在以下版本中已测试通过:
- capacitor: 8.0.0-ohos-8.0.0; SDK: 5.0.5(17); IDE: DevEco Studio: 6.0.0; ROM: 5.1.0.150;
权限要求
插件依赖OpenHarmony系统 ohos.permission.INTERNET 权限,需在应用中提前申请,否则将导致文件上传、下载功能失效。
OpenHarmony应用权限添加参考申请应用权限
,在主工程的 module.json5 的 requestPermissions 中添加 ohos.permission.INTERNET 权限,示例如下:
{
"name": "ohos.permission.INTERNET"
}使用示例
示例1:下载文件
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: '' // 空字符串获取目录路径
});
try {
// Then use the FileTransfer plugin to download
await FileTransfer.downloadFile({
url: 'https://example.com/file.pdf',
path: fileInfo.uri,
progress: true
});
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
console.error('下载文件失败:', errorMsg);
}
// Progress events
FileTransfer.addListener('progress', (progress) => {
console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`);
});示例2:上传文件
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: false,
progress: false
});
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
console.error('上传文件失败:', errorMsg);
}示例3:进度监听(上传/下载通用)
import { FileTransfer } from '@capacitor/file-transfer';
import { Filesystem, Directory } from '@capacitor/filesystem';
// 监听进度事件
const progressListener = await FileTransfer.addListener('progress', (progress) => {
// 计算进度百分比
const progressPercent = progress.contentLength ? Math.round((progress.bytes / progress.contentLength) * 100) : 0;
console.log(`传输进度:${progressPercent}%,已传输:${progress.bytes}字节,总大小:${progress.contentLength}字节`);
});
// 下载文件(带进度监听)
const fileInfo = await Filesystem.getUri({
directory: Directory.Documents,
path: 'document.pdf'
});
await FileTransfer.downloadFile({
url: 'https://example.com/document.pdf',
path: fileInfo.uri,
progress: true // 必须开启progress,否则不触发进度事件
});
// 移除监听(无需监听时调用)
await progressListener.remove();
// 移除所有监听
await FileTransfer.removeAllListeners();使用说明
FileTransfer是插件导出对象,可直接导入使用,导入后即可调用插件提供的所有方法,调用便捷高效,所有API均基于Promise实现,支持异步调用;使用前需确保已申请
ohos.permission.INTERNET 权限,适用于各类文件上传、下载及进度监听场景。
核心 API:FileTransfer 对象
FileTransfer 是插件导出对象,可直接导入使用,导入后即可调用插件提供的所有方法,调用便捷高效。依赖OpenHarmony系统
ohos.permission.INTERNET 权限。
方法列表与说明
| 方法名 | 返回类型 | 描述 | |--------------------------------------------|--------------------------------------------------------------|-----------------------| | downloadFile(options: DownloadFileOptions) | Promise<DownloadFileResult> | 将文件下载到指定位置 | | uploadFile(options: UploadFileOptions) | Promise<UploadFileResult> | 将文件上传到服务器 | | addListener('progress', ...) | Promise<PluginListenerHandle> | 添加文件传输(下载或上传)进度事件的监听器 | | removeAllListeners() | Promise<void> | 移除此插件的所有监听器 |
数据结构
DownloadFileResult
downloadFile 方法的返回结果对象,包含下载文件的相关信息。
| 属性 | 类型 | 描述 | 备注 | |------|--------|---------------|------------------------------| | path | string | 文件下载到的路径 | - | | blob | Blob | 下载文件的 blob 数据 | 仅在 Web 平台可用,OpenHarmony平台不支持 |
DownloadFileOptions
调用 downloadFile 方法时的入参对象,用于配置文件下载相关参数。
| 属性 | 类型 | 描述 | 备注 | |-----------------------|-------------|----------------------------------------------------------|---------------------------| | url | string | 用于下载文件的统一资源定位符(URL) | | | path | string | 下载文件应移动至的完整文件路径。可使用 @capacitor/filesystem 这类插件获取完整文件路径 | | | progress | boolean | 是否派发进度事件(progress event)。默认值为 false | | | method | string | HTTP请求方法。(默认值为 GET) | | | params | HttpParams | 需附加到请求中的 URL 参数 | | | headers | HttpHeaders | 需随请求一同发送的 HTTP 请求头 | | | readTimeout | number | 等待读取额外数据的时长(单位:毫秒)。每次接收到新数据时,该时长会重置。默认值为 60,000 毫秒(1 分钟) | OpenHarmony平台不支持 | | connectTimeout | number | 等待初始连接的时长(单位:毫秒)。默认值为 60,000 毫秒(1 分钟) | OpenHarmony平台api20及以上版本支持 | | disableRedirects | boolean | 设置是否应禁用 HTTP 自动重定向功能 | | | shouldEncodeUrlParams | boolean | 是否对URL参数进行编码。默认值为 true(即默认对 URL 参数进行编码) | |
UploadFileResult
uploadFile 方法的返回结果对象,包含文件上传的相关信息。
| 属性 | 类型 | 描述 | |--------------|----------------------------|----------------------| | bytesSent | number | 已上传的总字节数 | | responseCode | string | 上传操作的 HTTP 响应码 | | response | string | 上传操作的 HTTP 响应体(如果可用) | | headers | { [key: string]: string; } | 上传响应的 HTTP 头信息(如果可用) |
PluginListenerHandle
| 属性名 | 类型 | |--------|---------------------------| | remove | () => Promise<void> |
UploadFileOptions
调用 uploadFile 方法时的入参对象,用于配置文件上传相关参数。
| 属性 | 类型 | 描述 | 备注 | |-----------------------|-------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| | url | string | 用于上传文件的统一资源定位符(URL) | | | path | string | 待上传文件的完整文件路径。可使用 @capacitor/filesystem 这类插件获取完整文件路径 | | | blob | Blob | 待上传的二进制大对象(Blob)数据 | 仅在 Web 平台可用,OpenHarmony平台不支持 | | chunkedMode | boolean | 是否以分块流模式上传数据。Web 平台不支持此属性。注意:当 chunkedMode 设为 true(启用)时,上传请求将使用 Content-Type: multipart/form-data。根据后端服务器的配置,这可能导致上传失败。若服务器期望接收原始流数据(例如 application/octet-stream,二进制流类型),则必须在 headers中显式设置 Content-Type 头信息 | | | mimeType | string | 待上传数据的多用途互联网邮件扩展类型(MIME Type)。仅在未提供 "Content-Type"(内容类型)请求头时生效 | | | fileKey | string | 表单元素类型。默认值设为 "file"(文件)。仅在未提供 "Content-Type" 请求头时生效 | | | progress | boolean | 是否派发进度事件(progress event)。 默认值为 false | | | method | string | HTTP请求方法。(默认值为 POST) | | | params | HttpParams | 需附加到请求中的 URL 参数 | | | headers | HttpHeaders | 需随请求一同发送的 HTTP 请求头 | | | readTimeout | number | 等待读取额外数据的时长(单位:毫秒)。每次接收到新数据时,该时长会重置。默认值为 60,000 毫秒(1 分钟) | | | connectTimeout | number | 等待初始连接的时长(单位:毫秒)。默认值为 60,000 毫秒(1 分钟) | | | disableRedirects | boolean | 设置是否应禁用 HTTP 自动重定向功能 | | | shouldEncodeUrlParams | boolean | 是否对URL参数进行编码。默认值为 true(即默认对 URL 参数进行编码) | |
目录结构
|---- 目录
| |---- src/main # 插件的实现代码
| |----cpp # C++ 代码
| |----ets # ArkTS 代码
| |---- README.md # 说明文档
| |---- package.json # 配置文件
| |---- plugin.xml # 插件配置文件贡献代码
使用过程中发现任何问题都可以提 Issue ,当然,也非常欢迎发PR 共建。
许可证
本插件基于 MIT License 开源,详见 LICENSE 文件。
