基于 react-native-blob-util 的 OpenHarmony 适配版,二进制大对象处理(文件上传下载、Base64 转换)
文档模板:v0.4.2
react-native-blob-util
本项目基于 react-native-blob-util。
该第三方库的仓库已迁移至 Gitcode,并支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-blob-util,各版本对应关系如下:
| 三方库名称 | 三方库版本(npm 地址) | 发布信息 | 支持 RN 版本 | Autolink | 编译 API 版本 | 社区基线版本 | 源码地址 |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-blob-util | ~ 0.23.0 | Gitcode Releases | 0.82.*/0.84.* | 是 | API12+ | 0.24.10 | master |
| @react-native-ohos/react-native-blob-util | ~ 0.22.2 | Gitcode Releases | 0.77.* | 否 | API12+ | 0.21.1 | br_rnoh0.77 |
| @react-native-ohos/react-native-blob-util | ~ 0.19.8 | Gitcode Releases | 0.72.* | 是 | API12+ | 0.19.6 | br_rnoh0.72 |
| @react-native-oh-tpl/react-native-blob-util | <= 0.19.7@deprecated | Github Releases(deprecated) | 0.72.* | 否 | API12+ | 0.19.6 | sig |
简介
react-native-blob-util 是一款跨平台 RN 二进制网络文件与本地文件操作原生库,支持大文件上传下载与流式读写,可有效解决 fetch 处理二进制文件时的 OOM 问题。
下载安装
进入工程目录,并输入以下命令:
npm
npm install @react-native-ohos/react-native-blob-util
yarn
yarn add @react-native-ohos/react-native-blob-util
链接
| 是否支持 AutoLink | RN 框架版本 | |
|---|---|---|
| ~ 0.23.0 | 支持 | 0.82.*/0.84.* |
使用 AutoLink 的工程需要根据该文档进行配置,AutoLink 框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 AutoLink,并且工程已接入 AutoLink,可跳过 ManualLink 配置。
ManualLink:此步骤为手动配置原生依赖项的指导
首先需要使用 DevEco Studio 打开项目中的 HarmonyOS 工程 `harmony`。1. 覆盖 RN SDK
为了让工程依赖同一版本的 RN SDK,需要在工程根目录的 oh-package.json5 中添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本可以是具体的版本号,也可以是模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用,请阅读官方说明
{
"overrides": {
"@rnoh/react-native-openharmony": "^0.82.1" // ohpm 在线版本
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
}
}
2. 引入原生端代码
目前有两种方法:
- 通过 har 包引入;
- 直接链接源码。
方法一:通过 har 包引入(推荐)
har 包位于三方库安装路径的 `harmony` 文件夹下。
打开 entry/oh-package.json5,添加以下依赖
"dependencies": {
"@react-native-ohos/react-native-blob-util": "file:../../node_modules/@react-native-ohos/react-native-blob-util/harmony/blobUtil.har"
}
点击右上角的 sync 按钮
或者在命令行终端执行:
cd entry
ohpm install
方法二:直接链接源码
如需要使用直接链接源码,请参考[直接链接源码说明](https://gitcode.com/CPF-RN/usage-docs/blob/master/zh-cn/link-source-code.md)
3. 配置 CMakeLists 并引入 BlobUtilPackage
打开 entry/src/main/cpp/CMakeLists.txt,添加:
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-blob-util/src/main/cpp" ./blob-util)
# RNOH_END: manual_package_linking_1
file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)
# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_blob_util)
# RNOH_END: manual_package_linking_2
打开 entry/src/main/cpp/PackageProvider.cpp,添加:
#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "BlobUtilPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<SamplePackage>(ctx),
+ std::make_shared<RNBlobUtilPackage>(ctx),
};
}
4. 在 ArkTs 侧引入 BlobUtilPackage
打开 entry/src/main/ets/RNPackagesFactory.ts,添加:
+ import {BlobUtilPackage} from '@react-native-ohos/react-native-blob-util/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
+ new BlobUtilPackage(ctx)
];
}
运行
点击右上角的 sync 按钮
或在终端执行:
cd entry
ohpm install
随后编译、运行即可。
约束与限制
兼容性
本文档内容已在以下版本中验证通过:
- RNOH: 0.82.1; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 6.0.1 Release; ROM: 6.0.0.120 SP7;
- RNOH: 0.84.2; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 26.0.0 Beta1; ROM: 6.0.0.120 SP7;
权限要求
-
上传与下载需申请网络权限
在
entry/src/main/module.json5中添加
requestPermissions: [
{
name: "ohos.permission.INTERNET",
},
],
使用示例
以下代码演示了该库的基本用法:
使用时,import 的库名保持不变。
import React, { useState } from "react";
import {
ScrollView,
StyleSheet,
Button,
View,
Text
} from "react-native";
import ReactNativeBlobUtil from "react-native-blob-util";
export default function BlobUtilDemo() {
const [result, setResult] = useState<string | null>(null);
const [mkdirParam] = useState("blobUtilDemo");
const cacheDir = ReactNativeBlobUtil.fs.dirs.CacheDir;
const textFile = cacheDir + "/text.txt";
const textFileCopy = cacheDir + "/text1.txt";
const show = (value: unknown) => {
setResult(typeof value === "string" ? value : JSON.stringify(value));
};
const showError = (err: unknown) => {
const message = err instanceof Error ? err.message : String(err);
setResult(message);
};
const createFile = async () => {
try {
await ReactNativeBlobUtil.fs.createFile(textFile, "123456", "utf8");
show("createFile success");
} catch (err) {
showError(err);
}
};
const ls = async () => {
try {
const files = await ReactNativeBlobUtil.fs.ls(cacheDir);
show(files);
} catch (err) {
showError(err);
}
};
const unlink = async () => {
try {
await ReactNativeBlobUtil.fs.unlink(textFile);
show("unlink success");
} catch (err) {
showError(err);
}
};
const getConstants = () => {
show(cacheDir);
};
const writeFile = async () => {
try {
await ReactNativeBlobUtil.fs.writeFile(textFile, "Try to write str", "utf8");
show("writeFile success");
} catch (err) {
showError(err);
}
};
const writeStream = async () => {
try {
const stream = await ReactNativeBlobUtil.fs.writeStream(textFile, "utf8", false);
await stream.write("write stream data");
await stream.close();
show("writeStream success");
} catch (err) {
showError(err);
}
};
const writeArrayChunk = async () => {
try {
const stream = await ReactNativeBlobUtil.fs.writeStream(textFile, "ascii", false);
await stream.write([101, 32, 97]);
await stream.close();
show("writeArrayChunk success");
} catch (err) {
showError(err);
}
};
const writeChunk = async () => {
try {
const stream = await ReactNativeBlobUtil.fs.writeStream(textFile, "utf8", false);
await stream.write("Zm9vIChXcml0ZSBCYXNlNjQpMQ==");
await stream.close();
show("writeChunk success");
} catch (err) {
showError(err);
}
};
const closeStream = async () => {
try {
const stream = await ReactNativeBlobUtil.fs.writeStream(textFile, "utf8", false);
await stream.close();
show("closeStream success");
} catch (err) {
showError(err);
}
};
const readStream = async () => {
try {
const stream = await ReactNativeBlobUtil.fs.readStream(textFile, "utf8", 4000, 200);
let data = "";
stream.onData((chunk) => {
data += chunk;
});
stream.onError((err) => {
showError(err);
});
stream.onEnd(() => {
show(data);
});
stream.open();
} catch (err) {
showError(err);
}
};
const mkdir = async () => {
try {
const dir = ReactNativeBlobUtil.fs.dirs.DocumentDir + "/" + mkdirParam;
await ReactNativeBlobUtil.fs.mkdir(dir);
show("mkdir success: " + dir);
} catch (err) {
showError(err);
}
};
const stat = async () => {
try {
const info = await ReactNativeBlobUtil.fs.stat(textFile);
show(info);
} catch (err) {
showError(err);
}
};
const copyFileToCache = async () => {
try {
await ReactNativeBlobUtil.fs.cp(textFile, textFileCopy);
show("copyFileToCache success");
} catch (err) {
showError(err);
}
};
const writeFileArray = async () => {
try {
await ReactNativeBlobUtil.fs.writeFile(textFile, [102, 111, 111], "ascii");
show("writeFileArray success");
} catch (err) {
showError(err);
}
};
const exists = async () => {
try {
const fileExists = await ReactNativeBlobUtil.fs.exists(textFile);
show(String(fileExists));
} catch (err) {
showError(err);
}
};
const lstat = async () => {
try {
const info = await ReactNativeBlobUtil.fs.lstat(textFile);
show(info);
} catch (err) {
showError(err);
}
};
const mv = async () => {
try {
await ReactNativeBlobUtil.fs.mv(textFile, textFileCopy);
show("mv success");
} catch (err) {
showError(err);
}
};
const hash = async () => {
try {
const digest = await ReactNativeBlobUtil.fs.hash(textFile, "md5");
show(digest);
} catch (err) {
showError(err);
}
};
const readFile = async () => {
try {
const content = await ReactNativeBlobUtil.fs.readFile(textFile, "utf8", 4000);
show(content);
} catch (err) {
showError(err);
}
};
const slice = async () => {
try {
const dest = await ReactNativeBlobUtil.fs.slice(textFile, textFileCopy, 2, 5);
show(dest);
} catch (err) {
showError(err);
}
};
const df = async () => {
try {
const space = await ReactNativeBlobUtil.fs.df();
show(space);
} catch (err) {
showError(err);
}
};
return (
<View style={styles.container}>
<View style={styles.titleArea}>
<Text style={styles.title}>BlobUtil</Text>
</View>
<View style={styles.inputArea}>
<Text style={styles.baseText} ellipsizeMode="tail" numberOfLines={2}>{result}</Text>
</View>
<ScrollView style={styles.scrollView}>
<View style={{ flexDirection: "column" }}>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.getConstants()</Text>
<Button
title="运行"
color="#841584"
onPress={getConstants}
></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.createFile()</Text>
<Button title="运行" color="#841584" onPress={createFile}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.unlink()</Text>
<Button title="运行" color="#841584" onPress={unlink}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>
BlobUtilTurboModule.copyFileToCache()
</Text>
<Button
title="运行"
color="#841584"
onPress={copyFileToCache}
></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.writeFile()</Text>
<Button title="运行" color="#841584" onPress={writeFile}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.stat()</Text>
<Button title="运行" color="#841584" onPress={stat}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.mkdir()</Text>
<Button title="运行" color="#841584" onPress={mkdir}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.writeStream()</Text>
<Button title="运行" color="#841584" onPress={writeStream}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.ls()</Text>
<Button title="运行" color="#841584" onPress={ls}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>
BlobUtilTurboModule.writeFileArray()
</Text>
<Button
title="运行"
color="#841584"
onPress={writeFileArray}
></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.exists()</Text>
<Button title="运行" color="#841584" onPress={exists}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.lstat()</Text>
<Button title="运行" color="#841584" onPress={lstat}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.hash()</Text>
<Button title="运行" color="#841584" onPress={hash}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.readFile()</Text>
<Button title="运行" color="#841584" onPress={readFile}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.slice()</Text>
<Button title="运行" color="#841584" onPress={slice}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.df()</Text>
<Button title="运行" color="#841584" onPress={df}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.closeStream()</Text>
<Button title="运行" color="#841584" onPress={closeStream}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>
BlobUtilTurboModule.writeArrayChunk()
</Text>
<Button
title="运行"
color="#841584"
onPress={writeArrayChunk}
></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.writeChunk()</Text>
<Button title="运行" color="#841584" onPress={writeChunk}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.readStream()</Text>
<Button title="运行" color="#841584" onPress={readStream}></Button>
</View>
<View style={styles.baseArea}>
<Text style={{ flex: 1 }}>BlobUtilTurboModule.mv()</Text>
<Button title="运行" color="#841584" onPress={mv}></Button>
</View>
</View>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: "100%",
height: "100%",
flexDirection: "column",
alignItems: "center",
backgroundColor: "#F1F3F5",
},
baseText: {
width: "100%",
height: "100%",
fontWeight: "bold",
textAlign: "center",
fontSize: 16,
},
titleArea: {
width: "90%",
height: "8%",
alignItems: "center",
flexDirection: "row",
},
title: {
width: "90%",
color: "#000000",
textAlign: "left",
fontSize: 30,
},
scrollView: {
width: "90%",
marginHorizontal: 10,
},
inputArea: {
width: "90%",
height: "10%",
borderWidth: 2,
borderColor: "#000000",
marginTop: 8,
justifyContent: "center",
alignItems: "center",
},
baseArea: {
width: "100%",
height: 60,
borderRadius: 4,
borderColor: "#000000",
marginTop: 6,
backgroundColor: "#FFFFFF",
flexDirection: "row",
alignItems: "center",
paddingLeft: 8,
paddingRight: 8,
},
});
使用说明
下载
ReactNativeBlobUtil.config({
timeout: 20000,
})
.fetch("GET", "https://example.com/file.zip")
.then((res) => {
console.log("Downloaded to:", res.path());
})
.catch((err) => {
console.error(err);
});
上传
const filePath = ReactNativeBlobUtil.fs.dirs.CacheDir + '/fetch.txt';
ReactNativeBlobUtil.config({
timeout: 20000
})
.fetch(
"POST",
"https://example.com/file.zip",
{
'Content-Type': 'multipart/form-data',
},
[{
name: 'file',
filename: 'fetch.txt',
data: ReactNativeBlobUtil.wrap(filePath)
}]
)
.then((res) => {
if (res.data) {
console.log("fetch ok");
}
})
.catch((err) => {
console.error(err);
});
文件操作
const cacheDir = ReactNativeBlobUtil.fs.dirs.CacheDir;
const textFile = cacheDir + "/text.txt";
const textFileCopy = cacheDir + "/text1.txt";
// 获取缓存目录下的文件与文件夹列表
ReactNativeBlobUtil.fs.ls(cacheDir)
.then((files) => {
console.log("目录内容:", files);
})
.catch((err) => {
console.error(err);
});
// 删除指定文件 text.txt
ReactNativeBlobUtil.fs.unlink(textFile)
.then(() => {
console.log("unlink success");
})
.catch((err) => {
console.error(err);
});
// 以utf8编码向路径写入字符串
ReactNativeBlobUtil.fs.writeFile(textFile, "Try to write str", "utf8")
.then(() => {
console.log("writeFile success");
})
.catch((err) => {
console.error(err);
});
// 创建文件写入流,utf8编码,false = 不追加(覆盖模式)
ReactNativeBlobUtil.fs.writeStream(textFile, "utf8", false)
.then((stream) => stream.write("write stream data").then(() => stream.close()))
.then(() => {
console.log("writeStream success");
})
.catch((err) => {
console.error(err);
});
// 创建ascii编码写入流
ReactNativeBlobUtil.fs.writeStream(textFile, "ascii", false)
.then((stream) => stream.write([101, 32, 97]).then(() => stream.close()))
.then(() => {
console.log("writeArrayChunk success");
})
.catch((err) => {
console.error(err);
});
// 创建utf8覆盖写入流并关闭
ReactNativeBlobUtil.fs.writeStream(textFile, "utf8", false)
.then((stream) => stream.close())
.then(() => {
console.log("closeStream success");
})
.catch((err) => {
console.error(err);
});
// 创建文件读取流,utf8编码,分片最大4000字节,间隔200ms
ReactNativeBlobUtil.fs.readStream(textFile, "utf8", 4000, 200)
.then((stream) => {
let data = "";
stream.onData((chunk) => {
data += chunk;
});
stream.onError((err) => {
console.error(err);
});
stream.onEnd(() => {
console.log("readStream:", data);
});
stream.open();
})
.catch((err) => {
console.error(err);
});
// 在Document目录下创建新文件夹
ReactNativeBlobUtil.fs.mkdir(ReactNativeBlobUtil.fs.dirs.DocumentDir + "/blobUtilDemo")
.then(() => {
console.log("mkdir success");
})
.catch((err) => {
console.error(err);
});
// 获取文件stat信息(跟随软链接,读取目标文件元数据)
ReactNativeBlobUtil.fs.stat(textFile)
.then((info) => {
console.log("stat:", info);
})
.catch((err) => {
console.error(err);
});
// 复制文件
ReactNativeBlobUtil.fs.cp(textFile, textFileCopy)
.then(() => {
console.log("cp success");
})
.catch((err) => {
console.error(err);
});
// ascii编码写入字节数组
ReactNativeBlobUtil.fs.writeFile(textFile, [102, 111, 111], "ascii")
.then(() => {
console.log("writeFileArray success");
})
.catch((err) => {
console.error(err);
});
// 判断文件/目录是否存在
ReactNativeBlobUtil.fs.exists(textFile)
.then((fileExists) => {
console.log("exists:", fileExists);
})
.catch((err) => {
console.error(err);
});
// 获取lstat信息(不跟随软链接,读取链接自身元数据)
ReactNativeBlobUtil.fs.lstat(textFile)
.then((info) => {
console.log("lstat:", info);
})
.catch((err) => {
console.error(err);
});
// 移动文件(重命名)
ReactNativeBlobUtil.fs.mv(textFile, textFileCopy)
.then(() => {
console.log("mv success");
})
.catch((err) => {
console.error(err);
});
// 对文件计算md5哈希值
ReactNativeBlobUtil.fs.hash(textFile, "md5")
.then((digest) => {
console.log("hash:", digest);
})
.catch((err) => {
console.error(err);
});
// utf8读取文件内容
ReactNativeBlobUtil.fs.readFile(textFile, "utf8", 4000)
.then((content) => {
console.log("readFile:", content);
})
.catch((err) => {
console.error(err);
});
// 文件切片
ReactNativeBlobUtil.fs.slice(textFile, textFileCopy, 2, 5)
.then((dest) => {
console.log("slice:", dest);
})
.catch((err) => {
console.error(err);
});
接口说明
“Platform” 列表示该属性在原第三方库中支持的平台。
“OpenHarmony Support” 列值为 yes 表示 OpenHarmony 平台支持该属性;no 表示不支持;partially 表示部分支持。各平台的使用方法保持一致,实际效果与 iOS 或 Android 对齐。
组件
| 名称 | 参数类型 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|
| ReactNativeBlobUtil | ReactNativeBlobUtilStatic | yes | all | yes | ReactNativeBlobUtil 组件。 |
属性
Dirs
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| DocumentDir | string | "" | No | iOS, Android | Yes | 应用文档/文件目录,映射至 context.filesDir。 |
| CacheDir | string | "" | No | iOS, Android | Yes | 应用缓存目录,映射至 context.cacheDir。 |
| PictureDir | string | "" | No | iOS, Android | Yes | 图片目录,映射至 context.filesDir + '/picture'。 |
| LibraryDir | string | "" | No | iOS | No | iOS Library 目录。 |
| MusicDir | string | "" | No | iOS, Android | Yes | 音乐目录,映射至 context.filesDir + '/music'。 |
| MovieDir | string | "" | No | iOS, Android | Yes | 视频目录,映射至 context.filesDir + '/movie'。 |
| DownloadDir | string | "" | No | iOS, Android | Yes | 下载目录,映射至 context.filesDir(与 DocumentDir 相同)。 |
| DCIMDir | string | "" | No | Android | No | Android DCIM(相机照片)目录。 |
| SDCardDir | string | "" | No | Android | No | Android SD 卡根目录(已废弃)。 |
| SDCardApplicationDir | string | "" | No | Android | No | Android 应用专属 SD 卡目录(已废弃)。 |
| MainBundleDir | string | "" | No | iOS | Yes | iOS Main Bundle 目录,映射至 context.bundleCodeDir(Hap 资源包目录)。 |
| ApplicationSupportDir | string | "" | No | iOS | No | iOS Application Support 目录。 |
| LegacyPictureDir | string | "" | No | Android | No | Android 旧版图片目录。 |
| LegacyMusicDir | string | "" | No | Android | No | Android 旧版音乐目录。 |
| LegacyMovieDir | string | "" | No | Android | No | Android 旧版视频目录。 |
| LegacyDownloadDir | string | "" | No | Android | No | Android 旧版下载目录。 |
| LegacyDCIMDir | string | "" | No | Android | No | Android 旧版 DCIM 目录。 |
| LegacySDCardDir | string | "" | No | Android | No | Android 旧版 SD 卡目录(已废弃)。 |
ReactNativeBlobUtilConfig
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| Progress | { count?: number; interval?: number } | undefined | No | iOS, Android | Yes | 下载进度报告配置。 |
| UploadProgress | { count?: number; interval?: number } | undefined | No | iOS, Android | Yes | 上传进度报告配置。 |
| overwrite | boolean | true | No | iOS, Android | No | 是否覆盖已存在文件。 |
| timeout | number | 60000 | No | iOS, Android | Yes | 请求超时时间(毫秒)。 |
| indicator | boolean | false | No | iOS | No | 在 iOS 状态栏显示网络活动指示器。 |
| trusty | boolean | false | No | iOS, Android | No | 允许自签名 SSL 证书。 |
| wifiOnly | boolean | false | No | iOS, Android | No | 仅通过 WiFi 发起请求。 |
| followRedirect | boolean | true | No | iOS, Android | No | 是否跟随 HTTP 重定向。 |
| fileCache | boolean | false | No | iOS, Android | Yes | 将响应缓存为临时文件。 |
| transformFile | boolean | false | No | iOS, Android | No | 保存前通过 FileTransformer 处理数据。 |
| appendExt | string | "" | No | iOS, Android | Yes | 临时文件扩展名。 |
| path | string | "" | No | iOS, Android | Yes | 指定下载文件存储路径。 |
| session | string | "" | No | iOS, Android | No | 文件跟踪会话名称。 |
| addAndroidDownloads | AddAndroidDownloads | undefined | No | Android | No | Android Download Manager 集成配置。 |
| IOSBackgroundTask | boolean | false | No | iOS | No | 启用 iOS 后台 URL Session 模式。 |
| targetHostIp | string | "" | No | Android | No | targetHostIp 配置项,Android 平台支持多 STA 并发连接。 |
AddAndroidDownloads
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| useDownloadManager | boolean | false | No | Android | No | 使用 Android 系统 DownloadManager。 |
| title | string | "" | No | Android | No | 下载通知标题。 |
| description | string | "" | No | Android | No | 下载描述。 |
| path | string | "" | No | Android | No | 下载目标路径(须为外部存储)。 |
| mime | string | "text/plain" | No | Android | No | MIME 类型(默认 text/plain)。 |
| mediaScannable | boolean | false | No | Android | No | 使文件可被 MediaScanner 扫描到。 |
| storeInDownloads | boolean | false | No | Android | No | 存储到 MediaCollection Downloads(Android Q+)。 |
| notification | boolean | false | No | Android | No | 显示下载通知。 |
| storeLocal | boolean | false | No | Android | No | 保存到应用 Download 目录。 |
AndroidDownloadOption
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| title | string | / | Yes | Android | No | 文件加入下载应用时显示的标题。 |
| description | string | / | Yes | Android | No | 文件加入下载应用时显示的描述。 |
| mime | string | / | Yes | Android | No | 文件的 MIME 类型。 |
| path | string | / | Yes | Android | No | 文件的 URI 地址。 |
| showNotification | boolean | / | Yes | Android | No | 是否显示下载完成通知。 |
ReactNativeBlobUtilStat
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| lastModified | number | / | No | iOS, Android | Yes | 最后修改时间(时间戳)。 |
| size | number | / | No | iOS, Android | Yes | 文件大小(字节)。 |
| type | "directory" | "file" | / | No | iOS, Android | Yes | 路径类型:目录或文件。 |
| path | string | / | No | iOS, Android | Yes | 绝对路径。 |
| filename | string | / | No | iOS, Android | Yes | 文件或目录名。 |
RNFetchBlobDf
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| free | number | / | No | iOS, Android | Yes | 可用空间(字节,iOS/鸿蒙)。 |
| total | number | / | No | iOS, Android | Yes | 总空间(字节,iOS/鸿蒙)。 |
| external_free | string | / | No | Android | No | 外部存储可用空间。 |
| external_total | string | / | No | Android | No | 外部存储总空间。 |
| internal_free | string | / | No | Android | No | 内部存储可用空间。 |
| internal_total | string | / | No | Android | No | 内部存储总空间。 |
ReactNativeBlobUtilResponseInfo
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| taskId | string | / | No | iOS, Android | Yes | 请求任务 ID。 |
| state | string | / | No | iOS, Android | Yes | 请求状态。 |
| headers | any | / | No | iOS, Android | Yes | 响应头。 |
| redirects | string[] | / | No | iOS, Android | Yes | 重定向 URL 列表。 |
| status | number | / | No | iOS, Android | Yes | HTTP 状态码。 |
| respType | "text" | "blob" | "" | "json" | / | No | iOS, Android | Yes | 响应体类型。 |
| rnfbEncode | "path" | "base64" | "ascii" | "utf8" | / | No | iOS, Android | No | 响应体编码方式。 |
| timeout | boolean | / | No | iOS, Android | Yes | 请求是否超时。 |
Mediatype
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| Mediatype | "Audio" | "Image" | "Video" | "Download" | / | No | Android | No | MediaStore 媒体类型联合类型。 |
filedescriptor
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony 平台支持 | 描述 |
|---|---|---|---|---|---|---|
| path | string | / | Yes | Android | No | 媒体文件路径。 |
| parentFolder | string | / | Yes | Android | No | 媒体文件所在父目录名称。 |
| mimeType | string | / | Yes | Android | No | 媒体文件 MIME 类型。 |
API
ReactNativeBlobUtilStatic
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| fetch | function | (method: Methods, url: string, headers?: { [key: string]: string }, body?: any|null) | StatefulPromise<FetchBlobResponse> | 否 | iOS, Android | 支持 | 发起 HTTP(S) 请求(GET/POST/PUT/DELETE/PATCH),返回 StatefulPromise,支持进度回调与请求取消。 |
| base64 | { encode(input: string): string; decode(input: string): string }; | / | / | 否 | iOS, Android | 支持 | Base64 编码与解码工具对象,提供 encode 和 decode 方法。 |
| android | AndroidApi | / | / | 否 | iOS, Android | 不支持 | Android API 对象。 |
| ios | IOSApi | / | / | 否 | iOS, Android | 部分支持 | iOS API 对象。 |
| config | function | (options: ReactNativeBlobUtilConfig) | ReactNativeBlobUtilStatic | 否 | iOS, Android | 部分支持 | 注入请求配置,并返回携带该配置的 fetch 方法。 |
| session | function | (name: string) | ReactNativeBlobUtilSession | 否 | iOS, Android | 支持 | 获取或创建文件缓存会话。 |
| fs | FS | / | / | 否 | iOS, Android | 部分支持 | 文件系统操作命名空间。 |
| MediaCollection | MediaCollection | / | / | 否 | Android | 不支持 | Android MediaStore 集成能力。 |
| wrap | function | (path: string) | string | 否 | iOS, Android | 支持 | 将路径封装为带 ReactNativeBlobUtil-file:// 前缀的 URI。 |
| net | Net | / | / | 否 | iOS, Android | 不支持 | 网络工具,提供 getCookies 与 removeCookies。 |
| polyfill | Polyfill | / | / | 否 | iOS, Android | 不支持 | Web API Polyfill(Blob、File、XHR、Fetch 等)。 |
| JSONStream | function | (arg: string|Object) | any | 否 | iOS, Android | 不支持 | 流式 JSON 解析器(基于 Oboe.js)。 |
| CanceledFetchError | type | any | / | 否 | iOS, Android | 支持 | fetch 请求取消时抛出的自定义错误类型。 |
FS
ReactNativeBlobUtil.fs
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| ReactNativeBlobUtilSession | class | (name: string, list: string[]) | ReactNativeBlobUtilSession | 否 | iOS, Android | 部分支持 | 文件缓存会话构造类,可通过 new 创建会话实例。 |
| unlink | function | (path: string) | Promise<void> | 否 | iOS, Android | 支持 | 删除指定路径下的文件。 |
| mkdir | function | (path: string) | Promise<void> | 否 | iOS, Android | 支持 | 创建目录,支持递归创建。 |
| session | function | (name: string) | ReactNativeBlobUtilSession | 否 | iOS, Android | 支持 | 获取或创建文件缓存会话。 |
| ls | function | (path: string) | Promise<string[]> | 否 | iOS, Android | 支持 | 列出指定目录内容,返回文件名数组。 |
| hash | function | (path: string, algorithm: HashAlgorithm;OpenHarmony 仅支持 md5|sha1|sha256) | Promise<string> | 否 | iOS, Android | 部分支持 | 计算文件哈希。上游 HashAlgorithm 支持 md5/sha1/sha224/sha256/sha384/sha512;OpenHarmony 仅支持 md5/sha1/sha256(@ohos.file.hash)。 |
| readStream | function | (path: string, encoding: Encoding, bufferSize?: number, tick?: number) | Promise<ReactNativeBlobUtilReadStream> | 否 | iOS, Android | 支持 | 创建可读文件流,按数据块分发数据。 |
| mv | function | (path: string, dest: string) | Promise<boolean> | 否 | iOS, Android | 支持 | 移动或重命名文件。 |
| cp | function | (path: string, dest: string) | Promise<boolean> | 否 | iOS, Android | 支持 | 复制文件。 |
| writeStream | function | (path: string, encoding: Encoding, append?: boolean) | Promise<ReactNativeBlobUtilWriteStream> | 否 | iOS, Android | 支持 | 创建可写文件流。 |
| writeFile | function | (path: string, data: string|number[], encoding?: Encoding) | Promise<void> | 否 | iOS, Android | 支持 | 向文件写入数据,支持 utf8/base64/ascii。 |
| writeFileWithTransform | function | (path: string, data: string|number[], encoding?: Encoding) | Promise<void> | 否 | iOS, Android | 不支持 | 通过 FileTransformer 将数据写入文件。 |
| appendFile | function | (path: string, data: string|number[], encoding?: Encoding|"uri") | Promise<number> | 否 | iOS, Android | 支持 | 向文件追加数据。 |
| readFile | function | (path: string, encoding: Encoding, bufferSize?: number) | Promise<any> | 否 | iOS, Android | 支持 | 读取整个文件内容。 |
| readFileWithTransform | function | (path: string, encoding: Encoding, bufferSize?: number) | Promise<any> | 否 | iOS, Android | 不支持 | 通过 FileTransformer 读取文件。 |
| exists | function | (path: string) | Promise<boolean> | 否 | iOS, Android | 支持 | 检查文件或目录是否存在。 |
| createFile | function | (path: string, data: string|number[], encoding: Encoding) | Promise<void> | 否 | iOS, Android | 支持 | 创建新文件并写入内容。 |
| isDir | function | (path: string) | Promise<boolean> | 否 | iOS, Android | 支持 | 检查指定路径是否为目录。 |
| stat | function | (path: string) | Promise<ReactNativeBlobUtilStat> | 否 | iOS, Android | 支持 | 获取文件或目录元数据(size、lastModified、type、filename)。 |
| lstat | function | (path: string) | Promise<ReactNativeBlobUtilStat[]> | 否 | iOS, Android | 支持 | 列出目录条目及其元数据。 |
| scanFile | function | (pairs: Array<{ [key: string]: string }>) | Promise<void> | 否 | Android | 不支持 | 请求 Android MediaScanner 扫描文件。 |
| dirs | Dirs | / | / | 是 | iOS, Android | 支持 | 获取文件系统相关路径。 |
| slice | function | (src: string, dest: string, start: number, end: number) | Promise<string> | 否 | iOS, Android | 支持 | 将指定字节范围从源文件提取并写入目标文件。 |
| asset | function | (path: string) | string | 否 | iOS | 支持 | 将路径转换为 bundle-assets:// URI。 |
| df | function | / | Promise<RNFetchBlobDf> | 否 | iOS, Android | 支持 | 获取文件系统的可用空间与总空间。 |
| pathForAppGroup | function | (groupName: string) | Promise<string> | 否 | iOS | 不支持 | 获取 iOS App Group 共享容器路径。 |
| syncPathAppGroup | function | (groupName: string) | string | 否 | iOS | 不支持 | 同步获取 iOS App Group 共享容器路径 |
ReactNativeBlobUtilReadStream
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| open | function | / | void | 否 | iOS, Android | 支持 | 打开读取流并开始分发数据。 |
| onData | function | (fn: (chunk: string|number[]) => void) | void | 否 | iOS, Android | 支持 | 注册数据块回调。 |
| onError | function | (fn: (err: any) => void) | void | 否 | iOS, Android | 支持 | 注册错误回调。 |
| onEnd | function | (fn: () => void) | void | 否 | iOS, Android | 支持 | 注册读取结束回调。 |
| path | string | / | / | 否 | iOS, Android | 支持 | 读取流对应的文件路径。 |
| encoding | Encoding | / | / | 否 | iOS, Android | 支持 | 读取编码,支持 utf8、ascii、base64。 |
| bufferSize | number | / | / | 否 | iOS, Android | 支持 | 每次读取的缓冲区大小。 |
| closed | boolean | / | / | 否 | iOS, Android | 支持 | 流是否已关闭。 |
| tick | number | / | / | 否 | iOS, Android | 支持 | 分块读取的时间间隔,单位为毫秒。 |
ReactNativeBlobUtilWriteStream
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| write | function | (data: string|Array<any>) | Promise<void> | 否 | iOS, Android | 支持 | 向写入流写入数据。 |
| close | function | / | Promise<void> | 否 | iOS, Android | 支持 | 关闭写入流并释放资源。 |
| id | string | / | / | 否 | iOS, Android | 支持 | 原生写入流标识。 |
| encoding | string | / | / | 否 | iOS, Android | 支持 | 写入编码,支持 utf8、ascii、base64。 |
| append | boolean | / | / | 否 | iOS, Android | 不支持 | 是否以追加模式写入。 |
ReactNativeBlobUtilStream
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| onData | function | / | void | 否 | iOS, Android | 支持 | 数据分块到达时触发的回调。 |
| onError | function | / | void | 否 | iOS, Android | 支持 | 读取过程发生错误时触发的回调。 |
| onEnd | function | / | void | 否 | iOS, Android | 支持 | 读取结束时触发的回调。 |
StatefulPromise
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| cancel | function | (cb?: (reason: any) => void) | StatefulPromise<FetchBlobResponse> | 否 | iOS, Android | 支持 | 取消 HTTP 请求。 |
| progress | function | (config: { count?: number; interval?: number }, callback: (received: number, total: number) => void) | StatefulPromise<FetchBlobResponse> | 否 | iOS, Android | 支持 | 注册下载进度回调。 |
| uploadProgress | function | (config: { count?: number; interval?: number }, callback: (sent: number, total: number) => void) | StatefulPromise<FetchBlobResponse> | 否 | iOS, Android | 支持 | 注册上传进度回调。 |
| expire | function | (callback: () => void) | StatefulPromise<void> | 否 | iOS | 不支持 | iOS 后台任务到期回调(约 180 秒后触发)。 |
FetchBlobResponse
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| taskId | string | / | / | 否 | iOS, Android | 支持 | 任务 ID 字符串。 |
| path | function | / | string | 否 | iOS, Android | 支持 | 返回缓存的临时文件路径。 |
| type | "base64"|"path"|"utf8" | / | / | 否 | iOS, Android | 支持 | 响应数据类型,可为 "base64"、"path"、"utf8"。 |
| data | any | / | / | 否 | iOS, Android | 支持 | 原始响应数据。 |
| blob | function | (contentType: string, sliceSize: number) | Promise<PolyfillBlob> | 否 | iOS, Android | 支持 | 转换为 PolyfillBlob 对象。 |
| text | function | / | string|Promise<any> | 否 | iOS, Android | 支持 | 解码为文本字符串。 |
| json | function | / | any | 否 | iOS, Android | 支持 | 解析为 JSON 对象。 |
| base64 | function | / | any | 否 | iOS, Android | 支持 | 获取 Base64 编码字符串。 |
| flush | function | / | / | 否 | iOS, Android | 支持 | 删除响应缓存文件。 |
| respInfo | object | / | / | 否 | iOS, Android | 支持 | 响应元数据。 |
| info | function | / | ReactNativeBlobUtilResponseInfo | 否 | iOS, Android | 支持 | 获取响应信息。 |
| session | function | (name: string) | ReactNativeBlobUtilSession|null | 否 | iOS, Android | 支持 | 将响应文件加入指定会话。 |
| readFile | function | (encode: Encoding) | Promise<any>|null | 否 | iOS, Android | 支持 | 按指定编码读取缓存的响应文件。 |
| readStream | function | (encode: Encoding) | ReactNativeBlobUtilStream|null | 否 | iOS, Android | 支持 | 在缓存的响应文件上创建读取流。 |
Net
ReactNativeBlobUtil.net
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| getCookies | function | (domain: string) | Promise<string[]> | 否 | iOS, Android | 不支持 | 获取指定域名的 Cookie 列表。 |
| removeCookies | function | (domain?: string) | Promise<null> | 否 | iOS, Android | 不支持 | 删除指定域名的 Cookie。 |
IOSApi
ReactNativeBlobUtil.ios
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| previewDocument | function | (path: string, scheme?: string) | / | 否 | iOS | 是 | 预览文档。 |
| openDocument | function | (path: string, scheme?: string) | Promise<void> | 否 | iOS | 是 | previewDocument 的旧版别名。 |
| presentOptionsMenu | function | (path: string, scheme?: string) | / | 否 | iOS | 否 | 显示文档交互选项菜单。 |
| presentOpenInMenu | function | (path: string, scheme?: string) | / | 否 | iOS | 否 | 显示“打开方式”菜单。 |
| presentPreview | function | (path: string, scheme?: string) | / | 否 | iOS | 否 | 全屏预览。 |
| excludeFromBackupKey | function | (path: string) | Promise<void> | 否 | iOS | 否 | 标记文件或目录排除 iCloud/iTunes 备份。 |
AndroidApi
ReactNativeBlobUtil.android
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| actionViewIntent | function | (path: string, mime: string, chooserTitle?: string) | Promise<boolean|null> | 否 | Android | 否 | 发送 ACTION_VIEW Intent,以系统应用打开文件。 |
| getContentIntent | function | (mime: string) | Promise<void> | 否 | Android | 否 | 启动系统文件选择器,选择后返回文件 URI。 |
| addCompleteDownload | function | (options: AndroidDownloadOption) | Promise<void> | 否 | Android | 否 | 将已完成下载条目添加到系统下载应用。 |
| getSDCardDir | function | / | Promise<string> | 否 | Android | 否 | 获取 SD 卡根目录路径。 |
| getSDCardApplicationDir | function | / | Promise<string> | 否 | Android | 否 | 获取应用专属 SD 卡目录路径。 |
MediaCollection
ReactNativeBlobUtil.MediaCollection
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| copyToMediaStore | function | (filedata: filedescriptor, mediatype: Mediatype, path: string) | Promise<string> | 否 | Android | 否 | 将文件复制到 Android MediaStore。 |
| createMediafile | function | (filedata: filedescriptor, mediatype: Mediatype) | Promise<string> | 否 | Android | 否 | 在 MediaStore 中创建新文件条目。 |
| writeToMediafile | function | (uri: string, path: string) | Promise<string> | 否 | Android | 否 | 向 MediaStore 文件写入数据。 |
| writeToMediafileWithTransform | function | (uri: string, path: string) | Promise<string> | 否 | Android | 否 | 通过 FileTransformer 向 MediaStore 写入数据。 |
| copyToInternal | function | (contenturi: string, destpath: string) | Promise<string> | 否 | Android | 否 | 将 MediaStore 文件复制到应用内部存储。 |
| getBlob | function | (contenturi: string, encoding: string) | Promise<string> | 否 | Android | 否 | 将 MediaStore 文件数据读取为 Blob。 |
ReactNativeBlobUtilSession
ReactNativeBlobUtil.session
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| name | string | / | / | 否 | iOS, Android | 是 | 会话名称。 |
| add | function | (path: string) | ReactNativeBlobUtilSession | 否 | iOS, Android | 是 | 向此会话添加文件路径。 |
| remove | function | (path: string) | ReactNativeBlobUtilSession | 否 | iOS, Android | 是 | 从此会话中删除会话条目,但不删除文件。 |
| dispose | function | / | Promise<void> | 否 | iOS, Android | 是 | 删除会话中的所有文件。 |
| list | function | / | string[] | 否 | iOS, Android | 是 | 返回此会话中的文件路径数组。 |
| getSession | function | (name: string) | any | 否 | iOS, Android | 否 | 按名称获取会话路径列表。 |
| setSession | function | (name: string, val: any) | void | 否 | iOS, Android | 否 | 按名称设置会话路径列表。 |
| removeSession | function | (name: string) | void | 否 | iOS, Android | 否 | 按名称删除会话(不删除磁盘文件)。 |
Polyfill
ReactNativeBlobUtil.polyfill
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| Blob | PolyfillBlob | / | / | 否 | iOS, Android | 否 | Blob Polyfill 类。 |
| File | PolyfillFile | / | / | 否 | iOS, Android | 否 | File Polyfill 类(继承 PolyfillBlob)。 |
| XMLHttpRequest | PolyfillXMLHttpRequest | / | / | 否 | iOS, Android | 否 | XMLHttpRequest Polyfill 类。 |
| ProgressEvent | PolyfillProgressEvent | / | / | 否 | iOS, Android | 否 | ProgressEvent Polyfill 类。 |
| Event | PolyfillEvent | / | / | 否 | iOS, Android | 否 | Event Polyfill 类。 |
| FileReader | PolyfillFileReader | / | / | 否 | iOS, Android | 否 | FileReader Polyfill 类。 |
| Fetch | PolyfillFetch | / | / | 否 | iOS, Android | 否 | Fetch Polyfill 类。 |
EventTarget
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| addEventListener | function | (type: string, cb: () => void) | void | 否 | iOS, Android | 否 | 添加事件监听器。 |
| removeEventListener | function | (type: string, cb: () => void) | void | 否 | iOS, Android | 否 | 移除事件监听器。 |
| dispatchEvent | function | (type: string, event: Event) | void | 否 | iOS, Android | 否 | 派发事件。 |
| clearEventListeners | function | / | void | 否 | iOS, Android | 否 | 移除所有已注册的事件监听器(非标准)。 |
| listeners | object | / | / | 否 | iOS, Android | 否 | 已注册的事件监听器集合。 |
PolyfillBlob
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| onCreated | function | (fn: () => void) | PolyfillBlob | 否 | iOS, Android | 否 | 注册 Blob 创建完成事件回调。 |
| markAsDerived | function | / | void | 否 | iOS, Android | 否 | 将当前 Blob 标记为衍生 Blob。 |
| getReactNativeBlobUtilRef | function | / | string | 否 | iOS, Android | 否 | 获取 Blob 对应的文件引用路径。 |
| slice | function | (start?: number, end?: number, contentType?: string) | PolyfillBlob | 否 | iOS, Android | 否 | 对当前 Blob 进行切片,并返回新的 Blob 对象。 |
| readBlob | function | (encoding: string) | Promise<any> | 否 | iOS, Android | 否 | 按指定编码读取 Blob 数据(非标准)。 |
| close | function | / | Promise<void> | 否 | iOS, Android | 否 | 释放 Blob 对象资源(非标准)。 |
| clearCache(静态) | function | / | void | 否 | iOS, Android | 否 | 清空 Blob 缓存。 |
| build(静态) | function | (data: any, cType: any) | Promise<PolyfillBlob> | 否 | iOS, Android | 否 | 异步根据数据构建 Blob 对象。 |
| setLog(静态) | function | (level: number) | void | 否 | iOS, Android | 否 | 设置日志输出等级。 |
PolyfillFile
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| File | class | (data: any, cType: any, defer: boolean) | PolyfillFile | 否 | iOS, Android | 否 | File Polyfill 类,继承 PolyfillBlob。 |
PolyfillEvent
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| Event | class | / | / | 否 | iOS, Android | 否 | Event Polyfill 基类(空实现)。 |
PolyfillProgressEvent
| 名称 | 参数类型 | 默认值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|
| lengthComputable | boolean | / | 否 | iOS, Android | 否 | 进度总长度是否可计算。 |
| loaded | number | / | 否 | iOS, Android | 否 | 已加载字节数。 |
| total | number | / | 否 | iOS, Android | 否 | 总字节数。 |
PolyfillFileReader
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| isRNFBPolyFill | boolean | / | / | 否 | iOS, Android | 否 | 标识当前对象为 RNFB Polyfill 实现。 |
| onloadstart | function | (e: Event) | void | 否 | iOS, Android | 否 | 读取开始回调。 |
| onprogress | function | (e: Event) | void | 否 | iOS, Android | 否 | 读取进度回调。 |
| onload | function | (e: Event) | void | 否 | iOS, Android | 否 | 读取成功回调。 |
| onabort | function | (e: Event) | void | 否 | iOS, Android | 否 | 读取中止回调。 |
| onerror | function | (e: Event) | void | 否 | iOS, Android | 否 | 读取失败回调。 |
| onloadend | function | (e: Event) | void | 否 | iOS, Android | 否 | 读取结束回调。 |
| abort | function | / | void | 否 | iOS, Android | 否 | 中止当前读取操作。 |
| readAsArrayBuffer | function | (b: PolyfillBlob) | void | 否 | iOS, Android | 否 | 以 ArrayBuffer 方式读取 Blob。 |
| readAsBinaryString | function | (b: PolyfillBlob) | void | 否 | iOS, Android | 否 | 以二进制字符串方式读取 Blob。 |
| readAsText | function | (b: PolyfillBlob, label?: string) | void | 否 | iOS, Android | 否 | 以文本方式读取 Blob。 |
| readAsDataURL | function | (b: PolyfillBlob) | void | 否 | iOS, Android | 否 | 以 DataURL 方式读取 Blob。 |
| readyState | number | / | / | 否 | iOS, Android | 否 | 读取状态(EMPTY/LOADING/DONE)。 |
| result | any | / | / | 否 | iOS, Android | 否 | 读取结果数据。 |
| EMPTY(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:0,尚未加载数据。 |
| LOADING(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:1,数据加载中。 |
| DONE(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:2,读取已完成。 |
PolyfillXMLHttpRequestEventTarget
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| onabort | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求中止回调。 |
| onerror | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求失败回调。 |
| onload | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求加载完成回调。 |
| onloadstart | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求开始回调。 |
| onprogress | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求进度回调。 |
| ontimeout | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求超时回调。 |
| onloadend | function | (e: Event) | void | 否 | iOS, Android | 否 | 请求结束回调。 |
PolyfillXMLHttpRequest
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| upload | PolyfillXMLHttpRequestEventTarget | / | / | 否 | iOS, Android | 否 | 上传事件的目标对象。 |
| open | function | (method: string, url: string, async: true, user: any, password: any) | void | 否 | iOS, Android | 否 | 初始化 HTTP 请求(始终异步,不支持 user/password)。 |
| send | function | (body: any) | void | 否 | iOS, Android | 否 | 发送 HTTP 请求,并设置请求体。 |
| overrideMimeType | function | (mime: string) | void | 否 | iOS, Android | 否 | 覆盖响应 MIME 类型。 |
| setRequestHeader | function | (name: string, value: string) | void | 否 | iOS, Android | 否 | 设置请求头。 |
| abort | function | / | void | 否 | iOS, Android | 否 | 中止当前请求。 |
| getResponseHeader | function | (field: string) | string|null | 否 | iOS, Android | 否 | 获取指定响应头的值。 |
| getAllResponseHeaders | function | / | string|null | 否 | iOS, Android | 否 | 获取全部响应头。 |
| onreadystatechange | function | (e: Event) | void | 否 | iOS, Android | 否 | readyState 变化时的回调。 |
| readyState | number | / | / | 否 | iOS, Android | 否 | 当前请求状态。 |
| status | number | / | / | 否 | iOS, Android | 否 | HTTP 状态码。 |
| statusText | string | / | / | 否 | iOS, Android | 否 | HTTP 状态文本。 |
| response | any | / | / | 否 | iOS, Android | 否 | 响应体数据。 |
| responseText | any | / | / | 否 | iOS, Android | 否 | 响应文本数据。 |
| responseURL | string | / | / | 否 | iOS, Android | 否 | 响应 URL。 |
| responseHeaders | any | / | / | 否 | iOS, Android | 否 | 响应头对象。 |
| timeout | number | / | / | 否 | iOS, Android | 否 | 请求超时时间(毫秒)。 |
| responseType | string | / | / | 否 | iOS, Android | 否 | 响应类型。 |
| UNSENT(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:0,表示请求尚未初始化。 |
| OPENED(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:1,表示连接已建立。 |
| HEADERS_RECEIVED(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:2,表示响应头已接收。 |
| LOADING(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:3,表示响应体正在下载。 |
| DONE(静态) | number | / | / | 否 | iOS, Android | 否 | 状态常量:4,表示请求已完成。 |
| binaryContentTypes(静态) | string[] | / | / | 否 | iOS, Android | 否 | 二进制 Content-Type 列表。 |
| setLog(静态) | function | (level: number) | void | 否 | iOS, Android | 否 | 设置日志输出级别。 |
| addBinaryContentType(静态) | function | (substr: string) | void | 否 | iOS, Android | 否 | 添加自定义二进制 Content-Type。 |
| removeBinaryContentType(静态) | function | / | void | 否 | iOS, Android | 否 | 移除自定义二进制 Content-Type。 |
PolyfillFetch
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| PolyfillFetch | class | (config: ReactNativeBlobUtilConfig) | PolyfillFetch | 否 | iOS, Android | 否 | Fetch Polyfill 类,可通过对象组合(Object.assign)的方式接入 ReactNativeBlobUtilFetchPolyfill。 |
ReactNativeBlobUtilFetchPolyfill
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| build | function | / | (url: string, options: ReactNativeBlobUtilConfig) => StatefulPromise<ReactNativeBlobUtilFetchRepsonse> | 否 | iOS, Android | 否 | 构建符合 fetch 签名的请求函数。 |
ReactNativeBlobUtilFetchRepsonse
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
|---|---|---|---|---|---|---|---|
| arrayBuffer | function | / | Promise<any[]> | 否 | iOS, Android | 否 | 以 ArrayBuffer 方式读取响应体。 |
| blob | function | / | Promise<PolyfillBlob> | 否 | iOS, Android | 否 | 以 PolyfillBlob 方式读取响应体。 |
| json | function | / | Promise<any> | 否 | iOS, Android | 否 | 以 JSON 方式读取响应体。 |
| rawResp | function | / | Promise<FetchBlobResponse> | 否 | iOS, Android | 否 | 获取原始 FetchBlobResponse。 |
| text | function | / | Promise<string> | 否 | iOS, Android | 否 | 以文本方式读取响应体。 |
| bodyUsed | boolean | / | / | 否 | iOS, Android | 否 | 响应体是否已被读取。 |
| headers | any | / | / | 否 | iOS, Android | 否 | 响应头对象。 |
| ok | boolean | / | / | 否 | iOS, Android | 否 | 请求是否成功(2xx 状态码)。 |
| resp | FetchBlobResponse | / | / | 否 | iOS, Android | 否 | 原始响应对象。 |
| rnfbResp | FetchBlobResponse | / | / | 否 | iOS, Android | 否 | RNFB 原始响应对象。 |
| rnfbRespInfo | ReactNativeBlobUtilResponseInfo | / | / | 否 | iOS, Android | 否 | 响应元数据信息。 |
| status | number | / | / | 否 | iOS, Android | 否 | HTTP 状态码。 |
| type | string | / | / | 否 | iOS, Android | 否 | 响应类型。 |
遗留问题
其他
无
目录结构
/rntpc_react-native-blob-util # 项目根目录
├── harmony # 鸿蒙平台适配代码
│ └── blobUtil.har # 编译产出HAR静态包
│ └── blobUtil # 鸿蒙适配核心源码目录
│ └── Index.ets # 鸿蒙适配代码统一入口
│ └── ts.ets # ArkTS 类型导出入口文件
│ └── src/main
│ └── ets # ArkTS 业务实现层
│ └── BlobUtilTurboModule.ts # 鸿蒙侧TurboModule实现类
│ └── BlobUtilPackage.ets # RN原生模块Package注册类
└── generated # Codegen自动生成桥接代码
│ └── Logger.ets # 日志打印工具类
│ └── ReactNativeBlobUtil # 核心功能实现分组目录
│ └── ReactNativeBlobUtilImpl.ts # 顶层统一调度实现
│ └── ReactNativeBlobUtilFS.ts # 文件系统相关接口实现
│ └── ReactNativeBlobUtilReq.ts # 基础网络请求实现
│ └── ReactNativeBlobUtilStream.ts# 文件流读写逻辑实现
│ └── ReactNativeBlobUtilConfig.ts # 请求配置管理模块
│ └── turboModules # TurboModule 接口定义目录
│ └── down # 文件下载业务模块
│ └── upload # 文件上传业务模块
│ └── utils # 通用工具类目录
│ └── components # ArkUI页面组件目录
│ └── cpp # C++胶水层代码(RNOH桥接层)
│ └── BlobUtilPackage.h # C++层Package头文件
│ └── CMakeLists.txt # C++编译构建配置
│ └── generated # Codegen自动生成桥接代码(禁止手动修改)
├── example # Demo演示工程目录
├── README.md # 中文使用文档
└── README_en.md # 英文使用文档
贡献代码
使用过程中发现任何问题,都可以提交 Issue。当然,也非常欢迎提交 PR。
开源协议
本项目基于 The MIT License (MIT),请自由使用并参与开源。