diff --git a/FileUploadAndDownloadSlow/README.md b/FileUploadAndDownloadSlow/README.md new file mode 100644 index 0000000000000000000000000000000000000000..faee250bb55b4a891ecd0d51a0f8f32248ef05a2 --- /dev/null +++ b/FileUploadAndDownloadSlow/README.md @@ -0,0 +1,39 @@ +# 文件上传下载优化 + +## 项目简介 + +本示例是文件上传下载优化最佳实践中的代码示例片段。 + +## 效果预览 + + +## 使用说明 + +1. 本示例为最佳实践示例代码,开发者可以查阅官网最佳实践下文件上传下载优化最佳实践学习。 +2. 点击页面底部按钮Click me,查看日志打印压缩后的文件目录 + +## 工程目录 +``` +ets +├──entryability +│ └──EntryAbility.ets // 程序入口类 +├──entrybackupability +│ └──EntryBackupAbility.ets // 备份能力 +├──pages +│ └──ZipUploadPage.ets // 数据压缩页面 +└── resources // 资源目录内容不展开 +``` + +### 相关权限 + +不涉及。 + +### 约束与限制 + +1. 本示例仅支持标准系统上运行,支持设备:华为手机。 + +2. HarmonyOS系统:HarmonyOS 5.0.5 Release及以上。 + +3. DevEco Studio版本:DevEco Studio 5.0.5 Release及以上。 + +4. HarmonyOS SDK版本:HarmonyOS 5.0.5 Release SDK及以上。 \ No newline at end of file diff --git a/FileUploadAndDownloadSlow/entry/src/main/ets/entryability/EntryAbility.ets b/FileUploadAndDownloadSlow/entry/src/main/ets/entryability/EntryAbility.ets index 59f6b0bb6f0d844669ac31eb6676661dee11c1c6..707ad84d4002b3c860e71d04a4c57bca2f2e630d 100644 --- a/FileUploadAndDownloadSlow/entry/src/main/ets/entryability/EntryAbility.ets +++ b/FileUploadAndDownloadSlow/entry/src/main/ets/entryability/EntryAbility.ets @@ -1,3 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; @@ -24,7 +39,7 @@ export default class EntryAbility extends UIAbility { // Main window is created, set main page for this ability hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); - windowStage.loadContent('pages/Index', (err) => { + windowStage.loadContent('pages/ZipUploadPage', (err) => { if (err.code) { hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); return; diff --git a/FileUploadAndDownloadSlow/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets b/FileUploadAndDownloadSlow/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets index 8e4de99282050bad799ac892eb85ac5449364a51..0a97e21bd7a15599af76a806695860ff1eb0ebfe 100644 --- a/FileUploadAndDownloadSlow/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +++ b/FileUploadAndDownloadSlow/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets @@ -1,3 +1,18 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { hilog } from '@kit.PerformanceAnalysisKit'; import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit'; diff --git a/FileUploadAndDownloadSlow/entry/src/main/ets/pages/Index.ets b/FileUploadAndDownloadSlow/entry/src/main/ets/pages/Index.ets deleted file mode 100644 index 8e2d24ad42693fc877d51bb7820f0a9da68fa135..0000000000000000000000000000000000000000 --- a/FileUploadAndDownloadSlow/entry/src/main/ets/pages/Index.ets +++ /dev/null @@ -1,23 +0,0 @@ -@Entry -@Component -struct Index { - @State message: string = 'Hello World'; - - build() { - RelativeContainer() { - Text(this.message) - .id('HelloWorld') - .fontSize($r('app.float.page_text_font_size')) - .fontWeight(FontWeight.Bold) - .alignRules({ - center: { anchor: '__container__', align: VerticalAlign.Center }, - middle: { anchor: '__container__', align: HorizontalAlign.Center } - }) - .onClick(() => { - this.message = 'Welcome'; - }) - } - .height('100%') - .width('100%') - } -} \ No newline at end of file diff --git a/FileUploadAndDownloadSlow/entry/src/main/ets/pages/ZipUploadPage.ets b/FileUploadAndDownloadSlow/entry/src/main/ets/pages/ZipUploadPage.ets index 29f0002b300460b13aa270fcfbae901a0b60100d..0f99540fbe52afe507d04b3015a1c5f8ebbde672 100644 --- a/FileUploadAndDownloadSlow/entry/src/main/ets/pages/ZipUploadPage.ets +++ b/FileUploadAndDownloadSlow/entry/src/main/ets/pages/ZipUploadPage.ets @@ -1,7 +1,24 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // [Start import_zlib] import { common } from '@kit.AbilityKit'; import { fileIo } from '@kit.CoreFileKit'; -import { zlib } from '@kit.BasicServicesKit'; +import { BusinessError, zlib } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + // [End import_zlib] // [Start zip_upload] @@ -14,38 +31,86 @@ class ZipUpload { } // [End zip_upload] +@Entry @Component struct ZipUploadPage { private context: common.UIAbilityContext | undefined = undefined; private waitList: Array = []; + private filePath: string = ''; // [Start zip_upload_page] // Data compression processing async zipUploadFiles(fileUris: Array): Promise { - this.context = this.getUIContext().getHostContext() as common.UIAbilityContext; - let cacheDir = this.context.cacheDir; - let tempDir = fileIo.mkdtempSync(`${cacheDir}/XXXXXX`); - // Put the uri obtained from the library picture into fileUris and copy it to the temporary folder. - for (let i = 0; i < fileUris.length; i++) { - let fileName = fileUris[i].split('/').pop(); - let resourceFile: fileIo.File = fileIo.openSync(fileUris[i], fileIo.OpenMode.READ_ONLY); - fileIo.copyFileSync(resourceFile.fd, `${tempDir}/${fileName}`, 0); - fileIo.closeSync(resourceFile); + try { + this.context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let cacheDir = this.context.cacheDir; + let tempDir = fileIo.mkdtempSync(`${cacheDir}/XXXXXX`); + // Put the uri obtained from the library picture into fileUris and copy it to the temporary folder. + for (let i = 0; i < fileUris.length; i++) { + let fileName = fileUris[i].split('/').pop(); + let resourceFile: fileIo.File = fileIo.openSync(fileUris[i], fileIo.OpenMode.READ_ONLY); + fileIo.copyFileSync(resourceFile.fd, `${tempDir}/${fileName}`, 0); + fileIo.closeSync(resourceFile); + } + // File compression, package the previously generated temporary folder into test.zip + let options: zlib.Options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + }; + let data = await zlib.compressFile(tempDir, `${cacheDir}/test.zip`, options); + // Delete temporary folders + fileIo.rmdirSync(tempDir); + // Put the generated zip package into the transmission queue. + this.waitList.push(`${cacheDir}/test.zip`); + } catch (err) { + let error = err as BusinessError; + hilog.error(0x0000, 'FileUploadAndDownloadSlow', `zipUploadFiles error ${error.code} ${error.message}`); } - // File compression, package the previously generated temporary folder into test.zip - let options: zlib.Options = { - level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, - memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, - strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY - }; - let data = await zlib.compressFile(tempDir, `${cacheDir}/test.zip`, options); - // Delete temporary folders - fileIo.rmdirSync(tempDir); - // Put the generated zip package into the transmission queue. - this.waitList.push(`${cacheDir}/test.zip`); } // [End zip_upload_page] - build() { + async createSandboxFile() { + const context = this.getUIContext().getHostContext() as common.UIAbilityContext; + const dirPath = context.filesDir + '/myFiles'; + this.filePath = dirPath + '/data.txt'; + + try { + await fileIo.access(dirPath); + } catch { + await fileIo.mkdir(dirPath); + } + try { + const file = await fileIo.open(this.filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE); + await fileIo.write(file.fd, 'Sandbox file content'); + await fileIo.close(file.fd); + } catch (err) { + let error = err as BusinessError; + hilog.error(0x0000, 'FileUploadAndDownloadSlow', `zipUploadFiles error ${error.code} ${error.message}`); + } + } + + aboutToAppear(): void { + this.createSandboxFile(); + } + + build() { + Column() { + Button('Click me') + .width('100%') + .onClick(async () => { + if (this.filePath !== '') { + await this.zipUploadFiles([this.filePath]); + } + hilog.info(0x0000, 'FileUploadAndDownloadSlow', `${JSON.stringify(this.waitList)}`) + }) + } + .justifyContent(FlexAlign.End) + .width('100%') + .height('100%') + .padding({ + left: 16, + right: 16 + }) } } \ No newline at end of file diff --git a/FileUploadAndDownloadSlow/entry/src/main/resources/base/profile/main_pages.json b/FileUploadAndDownloadSlow/entry/src/main/resources/base/profile/main_pages.json index 1898d94f58d6128ab712be2c68acc7c98e9ab9ce..7d89202cb7de621c9e94985ce1590b2e6d64b02c 100644 --- a/FileUploadAndDownloadSlow/entry/src/main/resources/base/profile/main_pages.json +++ b/FileUploadAndDownloadSlow/entry/src/main/resources/base/profile/main_pages.json @@ -1,5 +1,5 @@ { "src": [ - "pages/Index" + "pages/ZipUploadPage" ] } diff --git a/FileUploadAndDownloadSlow/screenshot/index.png b/FileUploadAndDownloadSlow/screenshot/index.png new file mode 100644 index 0000000000000000000000000000000000000000..3ba485ea3b4cced28baf58887cbdced6e74a2382 Binary files /dev/null and b/FileUploadAndDownloadSlow/screenshot/index.png differ