介紹
本示例介紹在Worker子線程使用@ohos.zlib提供的zlib.compressfile接口對沙箱目錄中的文件進行壓縮操作,壓縮成功后將壓縮包所在路徑返回主線程,獲取壓縮文件列表。
效果圖預覽
使用說明
- 點擊壓縮按鈕,壓縮待壓縮文件,顯示壓縮結果。
下載安裝
- 模塊oh-package.json5文件中引入依賴
"dependencies": {
"@ohos/compressfile": "har包地址"
}
- ets文件import自定義視圖實現文件壓縮效果組件
import { CompressFileComponent } from '@ohos/compressfile';
快速使用
本節主要介紹了如何快速上手使用壓縮文件組件,包括構建壓縮組件以及常見自定義參數的初始化。
- 構建組件
在代碼合適的位置使用CompressFileComponent組件并傳入對應的參數,后續將介紹對應參數的初始化。
/**
* 構建壓縮組件
* compressBundleName: 壓縮成功后壓縮包的名字
* beCompressFileDir: 待壓縮文件所在目錄名
* compressZipPath: 壓縮成功后壓縮包路徑
*/
CompressFileComponent({
compressBundleName: this.compressBundleName,
beCompressFileDir: this.beCompressFileDir,
compressZipPath: this.compressZipDir,
})
- 各參數初始化,compressBundle可直接賦空,beCompressFileDir可直接賦值字符串,compressZipPath需指定路徑,格式為:目錄名/壓縮包名字。
@State compressBundleName: string = ''; // 壓縮成功后壓縮包名字
@State compressZipDir: string = 'bundlefile/compress_file.zip'; // 壓縮成功后壓縮包文件路徑
@State beCompressFileDir: string = 'compressfile'; // 待壓縮文件所在目錄名
屬性(接口)說明
CompressFileComponent組件屬性
屬性 | 類型 | 釋義 | 默認值 |
---|---|---|---|
compressBundle | string | 壓縮成功后壓縮包的名字 | - |
compressZipPath | string | 壓縮成功后壓縮包文件路徑 | - |
beCompressFileDir | string | 待壓縮文件在rawfile下和應用沙箱目錄下所在目錄名 | - |
實現思路
本示例通過主線程向子線程發送被壓縮文件目錄,壓縮文件名稱和沙箱路徑,在子線程中使用Zlib模塊提供的zlib.compressfile接口實現文件壓縮。
- 在/src/main/ets/worker目錄下創建Worker.ets線程文件,綁定Worker對象。
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;
- 在build-profile.json5中進行配置Worker線程文件路徑,Worker線程文件才能確保被打包到應用中。
"buildOption": {
"sourceOption": {
"workers": [
"./src/main/ets/workers/Worker.ets"
]
}
}
- 在主線程創建一個Worker線程,通過new worker.ThreadWorker()創建Worker實例,傳入Worker.ets的加載路徑。
let workerInstance: worker.ThreadWorker = new worker.ThreadWorker('@compressfile/ets/worker/Worker.ets');
- 主線程使用postMessage()向Worker線程發送應用沙箱路徑,壓縮包路徑和被壓縮文件所在目錄。
workerInstance.postMessage({
pathDir: this.pathDir,
compressZipPath: this.compressZipPath,
beCompressFileDir: this.beCompressFileDir
});
- 在Worker.ets文件中通過調用onmessage()方法接收主線程發送的應用沙箱路徑,壓縮文件名稱和壓縮文件目錄名稱。
workerPort.onmessage = (e: MessageEvents): void => {
logger.info(TAG, `Worker onmessage:${JSON.stringify(e.data)}`);
const pathDir: string = e.data.pathDir; // 沙箱目錄
const rawfileDirName: string = e.data.beCompressFileDir; // 被壓縮文件所在目錄名
// TODO: 知識點: 壓縮文件輸出路徑不能有特殊字符,否則會壓縮失敗
// 壓縮包輸出路徑
const outFilePath: string = `${pathDir}/${e.data.compressZipPath}`;
// 壓縮包輸出目錄
const outFileDir: string = outFilePath.slice(0, outFilePath.lastIndexOf('/'));
};
- 使用fs.access判斷輸出目錄是否已經存在,如果不存在使用fs.mkdirSync()創建空目錄用于放置壓縮后的文件。空目錄創建成功后使用zlib.compressFile接口壓縮文件,輸出到空目錄中。
fs.access(outFileDir, (err: BusinessError, res: boolean) => {
if (err) {
logger.error(TAG, `access failed with error message: ${err.message}, error code: ${err.code}`)
} else {
if (!res) {
fs.mkdirSync(outFileDir);
logger.info(TAG, 'mkdirSync succeed');
}
}
});
let options: zlib.Options = {
level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
};
try {
// 對目錄下的文件進行壓縮
zlib.compressFile(`${pathDir}/${rawfileZipName}`, outFile, options, (errData: BusinessError) => {
if (errData !== null) {
logger.error(TAG, `compress failed with error message: ${errData.message}, error code: ${errData.code}`);
} else {
workerPort.postMessage(outFileDir);
}
})
} catch (errData) {
let code = (errData as BusinessError).code;
let message = (errData as BusinessError).message;
logger.error(TAG, `compress errData is error code: ${code}, message: ${message}`);
}
高性能知識點
- 本示例使用在Work子線程中使用zlib.compressFile壓縮文件,避免阻塞主線程的運行。
工程結構&模塊類型
compressFile // har類型
|---/src/main/ets/components
| |---CompressFile.ets // 文件壓縮案例首頁
| |---CompressFileComponent.ets // 文件壓縮組件
|---/src/main/ets/worker
| |---Worker.ets // Worker線程
|---/src/main/ets/utils
| |---Logger.ets // 日志打印工具類
寫在最后
- 如果你覺得這篇內容對你還蠻有幫助,我想邀請你幫我三個小忙:
- 點贊,轉發,有你們的 『點贊和評論』,才是我創造的動力。
- 關注小編,同時可以期待后續文章ing??,不定期分享原創知識。
- 想要獲取更多完整鴻蒙最新學習知識點,請移步前往小編:
https://gitee.com/MNxiaona/733GH/blob/master/jianshu