@react-native-ohos/react-native-zip-archive
v6.1.2-1
Published
A little wrapper on ZipArchive for react-native
Downloads
598
Readme
文档模板:v0.4.2
本项目基于react-native-zip-archive 开发
该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-zip-archive 版本所属关系如下:
| 三方库名称 | 三方库版本(npm地址) | 发布信息 | 支持RN版本 | Autolink | 编译API版本 | 社区基线版本 | 源码地址 |
| - | - | - | - | - | - | - | - |
| @react-native-ohos/react-native-zip-archive | ~ 6.1.2 | Gitcode Releases | 0.72.* | 是 | API12+ | 6.1.1 | br_rnoh0.72 |
| @react-native-oh-tpl/react-native-zip-archive | <= 6.1.1-0.1.0@deprecated | Github Releases(deprecated) | 0.72.* | 否 | API12+ | 6.1.1 | sig |
简介
react-native-zip-archive 是一个用于处理 React Native 应用程序中 ZIP 文件的实用库。它提供了对文件或文件夹进行压缩和解压的功能,并可选择性地添加密码保护。
下载安装
进入到工程目录并输入以下命令:
npm
npm install @react-native-ohos/react-native-zip-archiveyarn
yarn add @react-native-ohos/react-native-zip-archiveLink
| | 是否支持autolink | RN框架版本 | | - | - | - | | ~6.1.2 | 是 | 0.72 |
使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。
首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。
1. Overrides RN SDK
为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用请阅读官方说明
{
"overrides": {
"@rnoh/react-native-openharmony": "^0.72.38" // ohpm 在线版本
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
}
}2. 引入原生端代码
目前有两种方法:
- 通过 har 包引入(在 IDE 完善相关功能后该方法会被遗弃,目前首选此方法);
- 直接链接源码。
方法一:通过 har 包引入(推荐)
[!TIP] har 包位于三方库安装路径的
harmony文件夹下。
打开 entry/oh-package.json5,添加以下依赖
"dependencies": {
"@rnoh/react-native-openharmony": "file:../react_native_openharmony",
"@react-native-ohos/react-native-zip-archive": "file:../../node_modules/@react-native-ohos/react-native-zip-archive/harmony/zipArchive_package.har"
}点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install方法二:直接链接源码
[!TIP] 如需使用直接链接源码,请参考直接链接源码说明
3. 配置 CMakeLists 和引入 zipArchive
打开 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(ZIP_ARCHIVE_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules/@react-native-ohos/react-native-zip-archive/src/main/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-zip-archive/src/main/cpp" ./zipArchive-package)
# RNOH_END: manual_package_linking_1
+ file(GLOB ZIP_ARCHIVE_GENERATED_CPP_FILES "${ZIP_ARCHIVE_CPP_DIR}/generated/*.cpp")
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
+ ${ZIP_ARCHIVE_GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
+ target_include_directories(rnoh_app PUBLIC ${ZIP_ARCHIVE_CPP_DIR})
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_zipArchive_package)
# RNOH_END: manual_package_linking_2打开 entry/src/main/cpp/PackageProvider.cpp,添加:
#include "RNOH/PackageProvider.h"
+ #include "ZipArchivePackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx)
{
return {
+ std::make_shared<ZipArchivePackage>(ctx),
};
}4. 在 ArkTs 侧引入 ZipArchivePackage
打开 entry/src/main/ets/RNPackagesFactory.ts,添加:
+ import {ZipArchivePackage} from '@react-native-ohos/react-native-zip-archive/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
new SamplePackage(ctx),
+ new ZipArchivePackage(ctx)
];
}运行
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install然后编译、运行即可。
约束与限制
兼容性
要使用此库,需要使用正确的 React-Native 和 RNOH 版本。另外,还需要使用配套的 DevEco Studio 和手机 ROM。
本文档内容基于以下版本验证通过:
- RNOH: 0.72.96; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
- RNOH: 0.72.33; SDK: HarmonyOS NEXT B1; IDE: DevEco Studio: 5.0.3.900; ROM: Next.0.0.71;
使用示例
下面的代码展示了这个库的基本使用场景:
[!WARNING] 使用时 import 的库名不变。demo用到的react-native-blob-util可以参考react-native-blob-util.md配置。
import React, { useState, useEffect } from 'react';
import { View, Button, StyleSheet, TextInput, Alert, Text, ActivityIndicator } from 'react-native';
import { pathParameters, zip, unzip, zipWithPassword, unzipWithPassword, subscribe, creteFile, isPasswordProtected, unzipAssets, getUncompressedSize } from 'react-native-zip-archive';
export default function ZipArchiveDemo() {
const [fileName, setFileName] = useState('');
const [fileContent, setFileContent] = useState('');
const [createdFilePath, setCreatedFilePath] = useState('');
const [compressedFilePath, setCompressedFilePath] = useState('');
const [newZipPath, setNewZipPath]: any = useState();
const [newSourcePath, setNewSourcePath]: any = useState();
const [newFolder, setNewFolder]: any = useState();
const [password, setPassword] = useState('');
const [showInput, setShowInput] = useState(false);
const [zipPassword, setZipPassword] = useState('');
const [progress, setProgress] = useState(0);
const [isProgressPing, setIsProgressPing] = useState<boolean>(false);
const [loading, setLoading] = useState(false);
const [unzipStatus, setUnzipStatus] = useState('');
const [uncompressSize, setUncompressSize] = useState('');
let unzipPassword: string = '';
let needPassword: boolean = false;
// 存储设置的密码
const setUnzipPassword = (value: string) => {
console.log(`setUnzipPassword: ${value}`);
unzipPassword = value;
}
useEffect(() => {
let filesDir = pathParameters(); // 获取 HarmonyOS 应用文件路径
let newZipPath: any = filesDir + '.zip';
let newSourcePath: any = filesDir;
let newFolder: any = filesDir + 'Out';//解压时新建个文件夹
setNewZipPath(newZipPath);//存储压缩包
setNewSourcePath(newSourcePath);//原文件路径
setNewFolder(newFolder);//解压时新建个文件夹
if (!showInput) {
setPassword(''); // 隐藏输入框时清空密码
}
}, [showInput]);
// 创建文件
const createFile = () => {
if (!fileName || !fileContent) {
Alert.alert('文件名和内容不能为空');
return;
}
const filePath = `${newSourcePath}/${fileName}.txt`;
if (fileName && fileContent) {
creteFile(filePath, fileContent)
.then(() => {
setCreatedFilePath(filePath);
Alert.alert('文件创建成功')
setTimeout(() => {
setFileName('');
setFileContent('');
}, 100);
})
.catch((error) => {
console.log('文件创建失败:', error);
});
} else {
Alert.alert('请输入文件名和内容');
}
};
// 密码压缩
const handleZipPress = () => {
if (password === '') {
Alert.alert('错误', '请输入密码');
return;
}
if (createdFilePath) {
handleProgress();//进度条
zipWithPassword(newSourcePath, newZipPath, password)
.then(() => {
console.log(`password--11:${password}`)
setZipPassword(password);
setCompressedFilePath(newZipPath)
Alert.alert('成功', '已使用密码创建压缩');
})
.catch(error => {
Alert.alert('错误', `创建压缩文件失败: ${error}`);
});
} else {
Alert.alert('无文件可供压缩');
}
};
// 解压时是否需要密码
const isUnzipWithPassword = () => {
if (unzipPassword) {
if (zipPassword === '') {
Alert.alert('错误', '请先进行压缩并设置密码');
return;
}
if (unzipPassword === zipPassword) {
handleGetUncompressedSize();
handleProgress();//进度条
unzipWithPassword(newZipPath,newFolder, unzipPassword)
.then(() => {
Alert.alert('成功', '已使用密码解压文件');
})
.catch(error => {
Alert.alert('错误', `解压文件失败: ${error}`);
});
} else {
Alert.alert('密码输入错误');
}
} else {
Alert.alert('错误', '请先输入密码');
}
}
// 密码解压&解压
const handleUnzipPress = () => {
if (this.needPassword) {
isUnzipWithPassword();
setShowInput(true);
return;
}
isPasswordProtected(newZipPath)
.then((res) => {
if (res) {
this.needPassword = true;
setShowInput(true);
} else {
if (compressedFilePath) {
if (needPassword === false) {
handleGetUncompressedSize();
handleProgress();//进度条
unzip(newZipPath, newFolder,'UTF-8')
.then(() => {
console.log(`unzip success`)
Alert.alert('成功', '已解压');
})
.catch(error => {
Alert.alert('错误', '解压失败');
console.log(`unzip error: ${error}`);
})
}
} else {
Alert.alert('无压缩文件可供解压');
}
}
})
.catch(error => {
console.error(`isPasswordProtected error: ${error}`)
})
}
// 进度条
const handleProgress = () => {
setIsProgressPing(true);
setProgress(0); //重置进度条
interface data {
progress: number,
filePath: string
}
let currentProgress = 0;
const interval = setInterval(() => {
if (currentProgress < 100) {
currentProgress += 20;
setProgress(currentProgress);
console.log(`current progress: ${currentProgress}%`);
} else {
clearInterval(interval); // 达到最大值后清除 interval
setIsProgressPing(false);
}
}, 1000);
subscribe((data: data) => {
try {
if (data.progress != null) {
currentProgress = data.progress;
setProgress(data.progress);
console.log(`subscribe success: ${data.progress}`);
setIsProgressPing(false);
if (data.progress === 100) {
clearInterval(interval);
}
}
} catch (error) {
console.log(`subscribe error: ${error}`);
clearInterval(interval);
}
})
}
// unzipAssets
const handleUnzipAssets = async () => {
setLoading(true);
let filesDir = pathParameters();
//解压files.zip文件到系统中的 destinationFolder 目录中
let assetPath = filesDir + '.zip';
let targetPath = filesDir + 'destinationFolder';
if (compressedFilePath) {
try {
await unzipAssets(assetPath, targetPath);
setUnzipStatus('解压完成');
console.log(`unzipAssets success`);
} catch (err) {
setUnzipStatus(`解压失败:${err}`);
console.log(`unzipAssets err: ${err}`);
} finally {
setLoading(false);
}
} else {
Alert.alert('无压缩文件可供解压');
}
}
// getUncompressedSize
const handleGetUncompressedSize = () => {
getUncompressedSize(newZipPath)
.then((uncompressSize:any) => {
setUncompressSize(uncompressSize);
console.log(`uncompressSize success:${uncompressSize}`)
})
.catch((err) => {
console.log(`getUncompressedSize err:${err}`)
})
}
return (
<View style={styles.content}>
<View style={styles.buttonSix}>
<View>
<Text>解压缩后的大小:{uncompressSize ? uncompressSize : '0'}字节</Text>
<View style={styles.progressBar}>
<View style={{ width: `${progress}%`, backgroundColor: '#00AEEF', height: '100%' }}></View>
</View>
<Text style={styles.percentageText}>{progress}%</Text>
</View>
</View>
<View >
<View >
<TextInput
placeholder="请输入文件名"
value={fileName}
onChangeText={setFileName}
style={{ borderWidth: 1, padding: 10, width: '70%' }}
/>
<TextInput
style={{
height: 100,
borderColor: 'gray',
borderWidth: 1,
width: 200,
padding: 10,
marginBottom: 10,
marginTop: 10
}}
onChangeText={text => setFileContent(text)}
value={fileContent}
placeholder="文件内容"
multiline={true}
/>
<Button title="创建文件" onPress={createFile} />
</View>
</View>
<View style={styles.buttonSix}>
<Button title='压缩' disabled={!createdFilePath} onPress={() => {
if (createdFilePath) {
handleProgress();//进度条
zip(newSourcePath, newZipPath)
.then(() => {
setCompressedFilePath(newZipPath)
Alert.alert('成功', '已压缩');
})
.catch(error => {
Alert.alert('错误', `压缩失败: ${error}`);
})
} else {
Alert.alert('无文件可供压缩');
}
}} />
</View>
<View>
<TextInput
style={styles.input}
placeholder="设置压缩密码"
onChangeText={text => setPassword(text)}
value={password}
/>
</View>
<View style={styles.buttonSix}>
<Button title='密码压缩' disabled={!createdFilePath} onPress={handleZipPress} />
</View>
{showInput && (
<View>
<TextInput
style={styles.input}
placeholder="输入解压密码"
onChangeText={text => setUnzipPassword(text)}
/>
</View>
)}
<View style={styles.buttonSix}>
<Button title="解压" disabled={!createdFilePath} onPress={handleUnzipPress} />
</View>
</View>
)
}
const styles = StyleSheet.create({
content: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
marginTop: 56
},
buttonSix: {
width: '65%',
marginBottom: 10,
marginTop: 20
},
input: {
borderWidth: 1,
padding: 10,
width: 300
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
progressBar: {
width: 250,
height: 20,
backgroundColor: '#E0E0E0',
borderRadius: 10,
overflow: 'hidden',
marginTop: 10
},
percentageText: {
marginTop: 5,
fontSize: 16
}
})使用说明
[!TIP] 以下示例中的
sourcePath、targetPath等路径需为鸿蒙应用可访问的沙箱路径,例如/data/storage/el2/base/haps/entry/files。路径中的file://前缀会被自动剥离,无需手动处理。
压缩文件
import { zip } from 'react-native-zip-archive';
// 压缩文件
zip(sourcePath, targetZipPath)
.then((path) => console.log('压缩完成:', path))
.catch((err) => console.log('压缩失败:', err));解压文件
import { unzip } from 'react-native-zip-archive';
// 解压到指定目录,charset 默认 'UTF-8'
unzip(zipPath, targetDir)
.then((path) => console.log('解压完成:', path));
// 指定编码(处理非 UTF-8 文件名)
unzip(zipPath, targetDir, 'GBK').then(...);密码压缩与解压
import { zipWithPassword, unzipWithPassword, isPasswordProtected } from 'react-native-zip-archive';
// 密码压缩:encryptionMethod 可选
zipWithPassword(sourcePath, targetZipPath, '123456')
.then((path) => console.log('密码压缩完成:', path));
// 密码压缩指定加密方式
zipWithPassword(sourcePath, targetZipPath, '123456', 'AES-256').then(...);
// 解压前先判断是否加密,再决定走密码解压还是普通解压
isPasswordProtected(zipPath).then((encrypted) => {
if (encrypted) {
unzipWithPassword(zipPath, targetDir, '123456')
.then((path) => console.log('密码解压完成:', path));
} else {
unzip(zipPath, targetDir).then(...);
}
});解压资源文件到指定目录
import { unzipAssets } from 'react-native-zip-archive';
// 将资源 zip 解压到目标目录(部分平台不支持,会抛出 "unzipAssets not supported on this platform")
unzipAssets(assetPath, targetDir)
.then((path) => console.log('解压完成:', path))
.catch((err) => console.log('解压失败:', err));获取解压后文件大小
import { getUncompressedSize } from 'react-native-zip-archive';
// 返回解压后总大小(字节),charset 默认 'UTF-8'
getUncompressedSize(zipPath)
.then((size) => console.log('解压后大小:', size, '字节'));监听压缩/解压进度
import { subscribe, zip } from 'react-native-zip-archive';
// subscribe 返回一个订阅句柄,progress 取值 0~100
const sub = subscribe((progress) => {
console.log(`进度: ${progress}%`);
});
zip(sourcePath, targetZipPath)
.then(() => {
console.log('完成');
sub.remove(); // 操作结束后移除监听,避免内存泄漏
})
.catch(() => sub.remove());[!WARNING]
subscribe返回的是全局事件监听,多个压缩/解压任务会复用同一通道。切换任务或组件卸载时务必调用sub.remove()清理,否则回调会串到错误任务的进度条上。
接口说明
[!TIP] "Platform"列表示该属性在原三方库上支持的平台。
[!TIP] "OpenHarmony Support"列为 yes 表示 OpenHarmony平台支持 该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
API
| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 |
| -------------------- | -------- | --------------------------------------------------------------------------------------------------- | ----------------------- | ---- | ---- | ------------------- | ----------------------------------------------------- |
| zip | function | (source: string \| string[], target: string) | Promise<string> | No | All | Yes | 压缩文件或文件夹(source 为数组时压缩多文件) |
| unzip | function | (source: string, target: string, charset?: string) | Promise<string> | No | All | Yes | 解压文件到指定目录,charset 解码压缩包内文件名,默认 UTF-8,支持 UTF-8/GBK/GB2312/Big5/Shift_JIS/sjis |
| zipWithPassword | function | (source: string \| string[], target: string, password: string, encryptionMethod?: string) | Promise<string> | No | All | Yes | 使用密码压缩文件或文件夹,source 为数组时压缩多文件,encryptionMethod 支持 STANDARD/AES-128/AES-256 |
| unzipWithPassword | function | (source: string, target: string, password: string) | Promise<string> | No | All | Yes | 使用密码解压文件 |
| isPasswordProtected | function | (source: string) | Promise<boolean> | No | All | Yes | 检查压缩文件是否存在密码保护 |
| unzipAssets | function | (source: string, target: string) | Promise<string> | No | All | Yes | 将资源 zip 文件解压到指定目录 |
| getUncompressedSize | function | (source: string, charset?: string) | Promise<number> | No | All | Yes | 获取压缩包解压后的文件大小,charset 解码压缩包内文件名,默认 UTF-8,支持 UTF-8/GBK/GB2312/Big5/Shift_JIS/sjis |
| subscribe | function | (callback: ({ progress, filePath }: { progress: number, filePath: string }) => void) | NativeEventSubscription | No | All | Yes | 订阅压缩/解压进度事件,回调入参 { progress, filePath },progress 取值 0~100(整数),filePath 为压缩/解压目标路径。返回 NativeEventSubscription(含 remove() 方法);事件为全局单通道、多任务共享,切换任务或卸载组件时须调用 remove() 清理。 |
遗留问题
其他
- 编译报错"Duplicated files found in module entry. This may cause unexpected errors at runtime. ERROR: 2 file found in 'lin\arm64-v8a\libz.so.1'..."
解决方案:该报错是从不同的包中收集到了相同名称的so包,名称为libz.so.1,导致so包冲突,可在模块级build-profile.json5文件中添加以下配置:
"buildOption": {
"nativeLib": {
"filter": {
"pickFirsts": ["**/libz.so.1"]
}
}
}目录结构
/rntpc_react-native-zip-archive # 项目根目录
├── harmony # 鸿蒙适配代码
│ └─ zipArchive_package.har # har 包
│ └─ zipArchive_package # 鸿蒙适配核心代码
│ └─ Index.ets # 鸿蒙适配代码入口
│ └─ ts.ets # ArkTS 侧类型导出入口
│ └─ libs # 原生 so 库
│ └─ src/main
│ └─ ets
│ └─ ZipArchiveTurboModule.ts # 鸿蒙侧 TurboModule 实现
│ └─ ZipArchivePackage.ets # 鸿蒙侧 Package
│ └─ cpp
│ └─ CMakeLists.txt # C++ 侧构建配置
│ └─ ZipArchivePackage.h # C++ 侧 Package
│ └─ generated # codegen 生成代码
│ └─ types / napi # 类型定义 / NAPI 接口
├── index.js # RN 侧入口(导出 zip/unzip 等 API)
├── index.d.ts # RN 侧类型定义
├── src
│ └─ NativeZipArchive.ts # codegen TurboModule 规范定义
├── example # 示例工程
├── README.md # 中文文档
├── README_en.md # 英文文档贡献代码
使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR 。
开源协议
本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。
