@cordova-ohos/cordova-plugin-file-transfer
v2.0.0
Published
Cordova File Transfer Plugin
Readme
cordova-plugin-file-transfer
Cordova 官方生态核心插件,提供跨平台的文件上传与下载功能,支持 HTTP/HTTPS 协议传输,适配本地文件系统操作(如 cordova-plugin-file 插件)。可实现大文件断点传输、进度监听、请求头自定义等核心能力,解决移动应用中文件传输的差异化问题,广泛用于图片上传、资源下载、日志同步等场景。本文档主要说明,该插件在OHOS系统中的应用。
核心特性
跨平台统一接口:一套代码适配 Android、iOS、OHOS 等平台,无需关注底层传输实现差异
完整文件传输能力:支持文件上传( multipart/form-data 格式)与下载(断点续传)
实时进度监听:提供上传 / 下载进度回调,支持显示进度条
灵活参数配置:支持自定义请求头、超时时间、文件 MIME 类型、表单字段等
错误处理机制:提供明确的错误码与描述,覆盖网络异常、文件不存在、权限不足等场景
安全传输支持:兼容 HTTPS 协议
依赖插件
该插件依赖 Cordova 文件系统插件实现本地文件操作,依赖cordova-plugin-file插件
安装指南
1. 基础安装(推荐)
通过 npm 安装最新稳定版,自动关联依赖插件:
# 安装hcordova
npm install -g hcordova
# 自动安装依赖的 cordova-plugin-file
hcordova plugin add cordova-plugin-file-transfer2. 安装指定版本
如需兼容特定 Cordova 或依赖插件版本,可指定版本号:
# 安装 1.0.0 稳定版
hcordova plugin add [email protected] --platform ohos3. 从 GitCode 安装开发版
如需测试最新功能或修复,可从 GitHub 仓库安装开发分支:
hcordova plugin add https://gitcode.com/OpenHarmony-Cordova/cordova-plugin-file-transfer.git --platform ohos4. 卸载插件
# 全平台卸载
hcordova plugin remove cordova-plugin-file-transfer
# 指定OHOS 卸载
hcordova plugin remove cordova-plugin-file-transfer --platform ohos
核心 API 文档
1. 构造函数:创建文件传输对象
// 初始化文件传输对象
const fileTransfer = new FileTransfer();2. 核心方法:上传文件
interface FileUploadOptions {
fileKey?: string; // 表单字段名,默认 "file"
fileName?: string; // 上传后的文件名,默认 "image.jpg"
mimeType?: string; // 文件 MIME 类型,默认 "image/jpeg"
params?: { [key: string]: string | number }; // 额外表单参数
chunkedMode?: boolean; // 是否分片传输,OHOS默认true
headers?: { [key: string]: string }; // 自定义请求头
httpMethod?: "POST" | "PUT"; // HTTP 方法,默认 "POST"
encodeURI?: boolean; // 是否自动编码 URL,默认 true
trustAllHosts?: boolean; // OHOS不校验域名
}
interface FileUploadResult {
bytesSent: number; // 已上传字节数
responseCode: number; // HTTP 响应码
response: string; // 服务端响应数据(字符串)
objectId: string; // 任务ID
}
fileTransfer.upload(
localFilePath: string | Blob, // 本地文件路径
serverUrl: string, // 服务端上传接口 URL
successCallback: (result: FileUploadResult) => void, // 成功回调
errorCallback: (error: FileTransferError) => void, // 失败回调
options?: FileUploadOptions, // 上传配置
trustAllHosts?: boolean // OHOS不校验域名
): void;3. 核心方法:下载文件
interface FileDownloadOptions {
headers?: { [key: string]: string }; // 自定义请求头
}
//下载结果是fileEntry对象
fileTransfer.download(
serverUrl: string, // 服务端文件 URL
localFilePath: string, // 本地保存路径
successCallback: (result: FileDownloadResult) => void, // 成功回调
errorCallback: (error: FileTransferError) => void, // 失败回调
trustAllHosts?: boolean, // 是否信任所有主机(SSL),默认 false
options?: FileDownloadOptions // 下载配置
): void;4. 事件:进度监听
// 上传/下载进度回调(共用同一个事件)
fileTransfer.onprogress = function(progressEvent: ProgressEvent) {
/**
* progressEvent 属性说明:
* - loaded:已传输字节数
* - total:总字节数(仅当服务端返回 Content-Length 时有效)
* - lengthComputable:是否可计算总进度(布尔值)
* - timeStamp:事件触发时间戳(毫秒)
*/
if (progressEvent.lengthComputable) {
const progress = (progressEvent.loaded / progressEvent.total) * 100;
console.log(`当前进度:${progress.toFixed(2)}%`);
} else {
console.log(`已传输:${(progressEvent.loaded / 1024 / 1024).toFixed(2)} MB`);
}
};5. 方法:取消传输
// 取消正在进行的上传/下载
fileTransfer.abort();上传 / 下载使用示例
1. 上传图片
//上传一张图片
function uploadPicture(imageUri) {
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
if(r.response == "MAX") { //服务端检测图片太大返回,具体以您的服务器返回修改
alert("图片太大超过4M,请剪裁小一点");
}
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
//alert('图片上传失败。');
}
//显示上传进度
function progressFun(progressEvent) {
var progress = progressEvent.loaded / progressEvent.total * 100;
document.getElementById("progress").innerHTML = "上传进度:"+progress+"%100";
}
//上传参数配置,具体您的服务器要求配置
var options = new FileUploadOptions();
options.fileKey = "picture";
options.fileName = imageUri.substr(imageUri.lastIndexOf('/')+1);
options.mimeType = "image/pjpeg";
var headers={'oss-token':'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGllbnRUeXBlIjoiYXBwIiwiaXNzIjoib3NzIiwidXNlclR5cGUiOjEsInNob3BJZCI6Ik1aIiwiZXhwIjoxNzU2MTA1NzY4LCJ1c2VySWQiOiJ5dHQifQ.VvjXxOxXtRHJQriCMBZJ_-szJJMwbe1qLbUD3kBmqCk'};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = progressFun;
ft.upload(imageUri, "https://your-server-domain/ImageTempUpload", win, fail, options);
//ft.abort();
}
function upload() {
var options = {
// Some common settings are 20, 50, and 100
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
// In this app, dynamically set the picture source, Camera or photo gallery
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
allowEdit: false,
correctOrientation: true //Corrects Android orientation quirks
}
//使用cordova-plugin-camera插件选择一个照片上传
navigator.camera.getPicture(function cameraSuccess(imageUri) {
var elem = document.getElementById('imageFile');
elem.src = imageUri;
window.resolveLocalFileSystemURL(imageUri, function (fileEntry) {
console.log(fileEntry.toURL());
uploadPicture(fileEntry.toURL());
});
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
}2. 下载图片
function download() {
function onErrorReadFile(error) {
}
function displayImage(blob) {
// Displays image if result is a valid DOM string for an image.
var elem = document.getElementById('imageFile2');
// Note: Use window.URL.revokeObjectURL when finished with image.
elem.src = window.URL.createObjectURL(blob);
}
function readBinaryFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
console.log("Successful file write: " + this.result);
//displayFileData(fileEntry.fullPath + ": " + this.result);
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
displayImage(blob);
//displayImage2(this.result);
};
reader.readAsArrayBuffer(file);
//reader.readAsDataURL(file);
//reader.readAsBinaryString(file);
}, onErrorReadFile);
}
function successFun(fileEntry) {
console.log("download complete: " + fileEntry.toURL());
readBinaryFile(fileEntry);
//document.getElementById("imageFile2").src = "https://localhost/"+fileEntry.toURL();
}
function failFun(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
alert('图片下载失败。');
}
function progressFun(progressEvent) {
var progress = progressEvent.loaded / progressEvent.total * 100;
document.getElementById("progress").innerHTML = "下载进度:"+progress+"%100";
}
var uri = "https://cordova.apache.org/static/img/cordova_bot.png";
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
var targetPath = dirEntry.toURL() + "中文.png";
console.log("targetPath:" + targetPath);
var fileTransfer = new FileTransfer();
fileTransfer.onprogress = progressFun;
fileTransfer.download(
uri,
targetPath,
successFun,
failFun,
false,
{}
);
//fileTransfer.abort();
});
}参数配置详解
1. 上传配置(FileUploadOptions)
| 参数名 | 类型 | 默认值 | 说明 |
| ------------- | -------------- | ------------ | ------------------------------------------- |
| fileKey | string | "file" | 服务端接收文件的表单字段名(如 PHP 中 $_FILES['file']) |
| fileName | string | "image.jpg" | 上传到服务端后的文件名,支持自定义扩展名(如 "video.mp4") |
| mimeType | string | "image/jpeg" | 文件的 MIME 类型,需与文件实际类型匹配(如 "application/pdf") |
| params | 对象 | {} | 额外的表单参数,服务端可通过请求体获取(如用户 ID、文件类型) |
| chunkedMode | boolean | true(移动平台) | 是否分片传输:- 大文件(>10MB)建议开启,减少内存占用- 小文件可关闭,提升效率 |
| headers | 对象 | {} | 自定义 HTTP 请求头(如认证 token、用户代理) |
| httpMethod | "POST" / "PUT" | "POST" | 上传使用的 HTTP 方法,需与服务端接口匹配 |
| encodeURI | boolean | true | 是否自动编码服务端 URL 中的特殊字符(如空格、中文) |
2. 下载配置(FileDownloadOptions)
| 参数名 | 类型 | 默认值 | 说明 |
| ----------------- | ------ | --- | --------------------------------- |
| headers | 对象 | {} | 自定义 HTTP 请求头(如 Accept、Cookie) |
错误码与处理方案
插件定义了标准化的错误码(FileTransferError),便于定位问题:
| 错误码 | 常量名 | 说明 | 常见原因与解决方案 |
| --- | ---------------------- | ------------------- | --------------------------------------------------- |
| 1 | FILE_NOT_FOUND_ERR | 本地文件不存在 | 1. 检查文件路径是否正确2. 确保应用有文件读取权限 |
| 2 | INVALID_URL_ERR | 服务端 URL 无效 | 1. 检查 URL 格式(如是否遗漏 http://)2. 使用 encodeURI 编码 URL |
| 3 | CONNECTION_ERR | 网络连接错误 | 1. 检查设备网络状态(WiFi/4G)2. 确认服务端接口可访问3. 处理超时(增大超时时间) |
| 4 | ABORT_ERR | 传输被主动取消 | 调用了 fileTransfer.abort(),属于正常流程,无需特殊处理 |
| 5 | NOT_MODIFIED_ERR | 文件未修改(HTTP 304) | 服务端返回 304 响应,说明本地文件已是最新版本,可停止下载 |
使用建议
不建议直接使用大文件上传或下载,如果应用进入后台,会被操作系统中断传输
许可证
本插件基于 Apache License 2.0 开源,详见 LICENSE 文件。
