diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/README_zh.md b/code/BasicFeature/Connectivity/UploadAndDownLoad/README_zh.md index a5e7b5a88257babe4b9a7265b5c1a971ee18c7b0..96dda84b854f57fe93d984aef97d5fc98c6989bb 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/README_zh.md +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/README_zh.md @@ -5,15 +5,15 @@ ### 效果预览 -| 主页 | 上传 | 片段上传 | 下载 | 证书锁定 | -| :---------------------------------------: | :---------------------------------------: | :--------------------------------------: | :--------------------------------------: | ---------------------------------------- | -| ![home](screenshots/devices/zh/home.jpg) | ![util](screenshots/devices/zh/upload.jpg) | ![util](screenshots/devices/zh/uploadchunk.jpg) | ![convertxml](screenshots/devices/zh/download.jpg) | ![cert_lock](screenshots/devices/zh/cert_lock.jpg) | +| 主页 | 上传 | 片段上传 | 下载 | 下载到用户目录 | 证书锁定 | +| :---------------------------------------: | :---------------------------------------: | :--------------------------------------: | :--------------------------------------: | :--------------------------------------: | ---------------------------------------- | +| ![home](screenshots/devices/zh/home.jpg) | ![util](screenshots/devices/zh/upload.jpg) | ![util](screenshots/devices/zh/uploadchunk.jpg) | ![convertxml](screenshots/devices/zh/download.jpg) | ![convertxml](screenshots/devices/zh/download_user.jpg) | ![cert_lock](screenshots/devices/zh/cert_lock.jpg) | 使用说明 1.本示例功能需要先配置服务器环境后使用,具体配置见[上传下载服务配置](./environment)。 -2.首页展示上传、下载和证书锁定三个入口组件,点击进入对应的页面,如果要使用后台下载任务,请开启后台任务开关。 +2.首页展示上传、下载、下载到用户目录和证书锁定四个入口组件,点击进入对应的页面,如果要使用后台下载任务,请开启后台任务开关。 3.上传页面: @@ -103,9 +103,9 @@ UploadAndDownload * 下载模块 - * 使用[@ohos.request](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-request.md)中API 12接口agent.create创建上传任务,调用@ohos.request中的Task相关接口实现上传任务的创建、取消、进度加载,失败的任务会调用查询接口获取失败原因并打印在日志中,前台下载任务只支持单个文件下载,后台下载任务支持多文件下载。使用[@ohos.file.fs](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-core-file-kit/js-apis-file-fs.md)完成指定路径的创建和查询已下载的文件。 + * 使用[@ohos.request](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-request.md)中API 12接口agent.create创建下载任务,调用@ohos.request中的Task相关接口实现下载任务的创建、取消、进度加载,失败的任务会调用查询接口获取失败原因并打印在日志中,前台下载任务只支持单个文件下载,后台下载任务支持多文件下载,下载到用户目录只支持前台下载。使用[@ohos.file.fs](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-core-file-kit/js-apis-file-fs.md)完成指定路径的创建和查询已下载的文件。使用[@ohos.file.picker](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-core-file-kit/js-apis-file-picker.md)进行用户文件的目录路径选择和查看。 * 源码链接:[RequestDownload.ets](./features/uploadanddownload/src/main/ets/download/RequestDownload.ets),[Download.ets](./entry/src/main/ets/pages/Download.ets),[FileUtils.ets](./features/uploadanddownload/src/main/ets/utils/FileUtils.ets),[FileBrowse.ets](./features/uploadanddownload/src/main/ets/components/FileBrowse.ets) - * 参考接口:[@ohos.request](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-request.md),[@ohos.file.fs](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-core-file-kit/js-apis-file-fs.md) + * 参考接口:[@ohos.request](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-request.md),[@ohos.file.fs](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-core-file-kit/js-apis-file-fs.md),[@ohos.file.picker](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-core-file-kit/js-apis-file-picker.md) * 证书锁定模块 @@ -133,9 +133,9 @@ UploadAndDownload 1.本示例仅支持标准系统上运行,支持设备:RK3568。 -2.本示例为Stage模型,支持API12版本SDK,SDK版本号(API Version 12),镜像版本号(5.0) +2.本示例为Stage模型,支持API20版本SDK,SDK版本号(API Version 20),镜像版本号(6.0) -3.本示例需要使用DevEco Studio 版本号(4.1 Release)及以上版本才可编译运行。 +3.本示例需要使用DevEco Studio 版本号(5.0.5 Release)及以上版本才可编译运行。 4.运行本示例需全程联网。 diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/build-profile.json5 b/code/BasicFeature/Connectivity/UploadAndDownLoad/build-profile.json5 index 49dfabaaebd6ee47414f91c55299f79b16629226..875dfdc5350b40a55965a4d52b663394ba85139a 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/build-profile.json5 +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/build-profile.json5 @@ -21,8 +21,8 @@ { "name": "default", "signingConfig": "default", - "compileSdkVersion": 12, - "compatibleSdkVersion": 12, + "compileSdkVersion": 20, + "compatibleSdkVersion": 20, "runtimeOS": "OpenHarmony" } ] diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/build-profile.json5 b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/build-profile.json5 index 6ebd7bd06c2022dfa7a8fd08b0d983476bf08252..74bd2c087893b6e7ea5471d82b35f454b7751c43 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/build-profile.json5 +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/build-profile.json5 @@ -20,8 +20,6 @@ "targets": [ { "name": "default" - , - "runtimeOS":"OpenHarmony" } , { diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Download.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Download.ets index 86f662222dd22f84372d6ee674273b61a430513b..46e6cbaf4ac07a6c23e8f2c0d6ba8b3b21d47154 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Download.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Download.ets @@ -27,25 +27,32 @@ import { TOAST_BOTTOM } from '@ohos/uploaddownload'; import { SelectFolderDialog } from '../components/SelectFolderDialog'; +import { common } from '@kit.AbilityKit'; +import { picker } from '@kit.CoreFileKit'; +import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = 'DownloadSample'; +const userDir: string = 'file://docs/storage/Users/currentUser'; @Entry @Component struct Download { private fileData: CustomDataSource = new CustomDataSource([]); + private documentSelectOptions = new picker.DocumentSelectOptions(); @StorageLink('isBackground') isBackground: boolean = false; @StorageLink('backDownTaskState') backDownTaskState: BackgroundTaskState = BackgroundTaskState.NONE; + @StorageLink('downloadServer') downloadServerStr: string = './'; @Provide downloadFolder: Array = []; @State isGetData: boolean = false; @State checkFile: Array = []; @State checkList: Array = []; @State isRunning: boolean = false; + @State isUserFolder: boolean = true; @State isPause: boolean = false; @State progress: number = 0; private selectFolder = (folder: string) => { logger.info(TAG, `selectFolder = ${folder}`); - this.download(folder); + this.download('./' + folder); } private folderDialogController: CustomDialogController = new CustomDialogController({ builder: SelectFolderDialog({ selectFolder: this.selectFolder }), @@ -53,6 +60,56 @@ struct Download { alignment: DialogAlignment.Bottom, offset: { dx: 0, dy: -12 } }); + async selectUserFolder() { + const documentSaveOptions = new picker.DocumentSaveOptions(); + logger.info(TAG, `documentSaveOptions: ${JSON.stringify(documentSaveOptions)}`) + logger.info(TAG, `documentSelectOptions: ${JSON.stringify(this.documentSelectOptions)}`) + this.checkFile = []; + if (this.checkList === undefined) { + return; + } + logger.info(TAG, `checkList = ${JSON.stringify(this.checkList)}`); + for (let i = 0; i < this.checkList.length; i++) { + if (this.checkList[i]) { + let fileModel = this.fileData.getData(i); + logger.info(TAG, `fileModel = ${JSON.stringify(fileModel)}`); + fileModel.files.forEach((url: string) => { + let splitUrl = url.split('//')[1].split('/'); + if (splitUrl[splitUrl.length-1] !== '') { + this.checkFile.push(url); + documentSaveOptions.newFileNames = [splitUrl[splitUrl.length-1]]; + } + }); + } + } + + logger.info(TAG, `checkFile = ${JSON.stringify(this.checkFile)}`); + + if (this.checkFile.length === 0) { + promptAction.showToast({ message: $r('app.string.check_file_tips'), bottom: TOAST_BOTTOM }); + return; + } + + logger.info(TAG, `documentSaveOptions: ${documentSaveOptions}`) + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + logger.info(TAG, `context: ${JSON.stringify(context)}`) + const documentViewPicker = new picker.DocumentViewPicker(context); + logger.info(TAG, `documentViewPicker: ${JSON.stringify(documentViewPicker)}`) + await documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array) => { + logger.info(TAG, `documentSaveResult: ${documentSaveResult}`) + let splitUrl = documentSaveResult[0].split('/'); + logger.info(TAG, `splitUrl: ${splitUrl}`) + splitUrl.pop(); + logger.info(TAG, `splitUrl: ${splitUrl}`) + let splitUrl1=splitUrl.join('/'); + logger.info(TAG, `selectFolder = ${splitUrl1}`); + this.documentSelectOptions.defaultFilePathUri = splitUrl1 + this.download(splitUrl1); + logger.info(TAG, `selectFolder = ${splitUrl1}`); + }).catch((err: BusinessError) => { + logger.error(TAG, `code : ${err.code} message : ${err.message}`) + }); + } build() { Navigation() { @@ -91,7 +148,7 @@ struct Download { .mode(NavigationMode.Stack) .backgroundColor($r('app.color.light_gray')) .hideToolBar(false) - .title($r('app.string.download')) + .title(this.isUserFolder?$r('app.string.downloadToUser'):$r('app.string.download')) } @Builder @@ -192,7 +249,7 @@ struct Download { .fontSize(16) .margin({ left: 12 }) } else { - Text($r('app.string.download')) + Text(this.isUserFolder?$r('app.string.downloadToUser'):$r('app.string.download')) .fontColor(Color.White) .fontSize(16) } @@ -203,9 +260,13 @@ struct Download { .height(45) .width('100%') .backgroundColor($r('app.color.button_blue')) - .onClick(() => { + .onClick(async () => { if (!this.isRunning) { - this.folderDialogController.open(); + if (this.isUserFolder ) { + await this.selectUserFolder(); + } else { + this.folderDialogController.open(); + } } }) } @@ -218,9 +279,22 @@ struct Download { .margin({ bottom: 12 }) .fontColor($r('app.color.btn_text_blue')) .onClick(() => { - router.pushUrl({ - url: 'pages/DownloadFiles' - }); + if (this.isUserFolder ) { + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + logger.info(TAG, `context: ${JSON.stringify(context)}`) + const documentViewPicker = new picker.DocumentViewPicker(context); + logger.info(TAG, `documentViewPicker: ${JSON.stringify(documentViewPicker)}`) + logger.info(TAG, `documentSelectOptions: ${JSON.stringify(this.documentSelectOptions)}`) + documentViewPicker.select(this.documentSelectOptions).then((documentSelectResult: Array) =>{ + logger.info(TAG, `documentSelectResult: ${documentSelectResult}`) + }) + } else { + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + AppStorage.setOrCreate('downloadDir', context.cacheDir); + router.pushUrl({ + url: 'pages/DownloadFiles' + }) + } }) } .margin({ top: 12, left: 12, right: 12 }) @@ -231,19 +305,45 @@ struct Download { this.isRunning = false; this.isPause = false; this.isGetData = true; - requestFiles.requestFiles().then((data: FileModel[]) => { + const params = router.getParams(); + logger.info(`router.params: ${params}`); + if (params) { + this.isUserFolder=true; this.checkList = []; - this.isRunning = false; - this.fileData.dataArray = data; + this.isRunning = false; + let itemtxt:FileModel = new FileModel('test.txt',false,[this.downloadServerStr + 'test.txt']); + let itemjpg:FileModel = new FileModel('edge_picture.jpg',false,[this.downloadServerStr + 'edge_picture.jpg']); + let itemmp3:FileModel = new FileModel('audio_test.mp3',false,[this.downloadServerStr + 'audio_test.mp3']); + let itemmp4:FileModel = new FileModel('video_media.mp4',false,[this.downloadServerStr + 'video_media.mp4']); + this.fileData.dataArray = [itemtxt,itemjpg,itemmp3,itemmp4] ; this.fileData.dataArray.forEach((item: FileModel) => { + logger.debug(TAG, `item:${JSON.stringify(item)}`); this.checkList.push(false); }) this.isGetData = false; this.fileData.notifyDataReload(); - }) - fileUtils.listFolders().then((folders: Array) => { - this.downloadFolder = folders; - }) + fileUtils.listFolders(userDir).then((folders: Array) => { + logger.debug(TAG, `folders:${JSON.stringify(folders)}`); + this.downloadFolder = folders; + }) + } else { + this.isUserFolder=false; + requestFiles.requestFiles().then((data: FileModel[]) => { + this.checkList = []; + this.isRunning = false; + this.fileData.dataArray = data; + this.fileData.dataArray.forEach((item: FileModel) => { + this.checkList.push(false); + }) + this.isGetData = false; + this.fileData.notifyDataReload(); + }) + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + fileUtils.listFolders(context.cacheDir).then((folders: Array) => { + logger.debug(TAG, `folders:${JSON.stringify(folders)}`); + this.downloadFolder = folders; + }) + } } fileCheck(index: number) { diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/DownloadFiles.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/DownloadFiles.ets index 490bb2661208f0a54d359994c9c4b7c8fa03e10d..212b3c24f0785ccefa3ee6871b69205c42bd1f21 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/DownloadFiles.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/DownloadFiles.ets @@ -18,9 +18,10 @@ import { FileBrowse } from '@ohos/uploaddownload'; @Entry @Component struct DownLoadFiles { + @StorageLink('downloadDir') downloadDir: string = './'; build() { Column() { - FileBrowse() + FileBrowse({downloadDir:this.downloadDir}) } .width('100%') .height('100%') diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Index.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Index.ets index a2ed4f2e8e9a7474c0a19f792de9ef08d864266c..cfcacb89500e90e4aab037d1cc1061f9091e2fe5 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Index.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Index.ets @@ -17,7 +17,8 @@ import notificationManager from '@ohos.notificationManager'; import router from '@ohos.router'; import common from '@ohos.app.ability.common'; import { urlUtils } from '@ohos/uploaddownload'; -import util from '@ohos.util'; +import { promptAction } from '@kit.ArkUI'; + @Styles function itemStyle() { @@ -65,6 +66,11 @@ struct Index { .itemStyle() .margin({ top: 20 }) + TextInput({ text: $r('app.string.downloadServer') }) + .visibility(Visibility.Hidden) + .height(0) + .onChange((downloadServer) => AppStorage.setOrCreate('downloadServer', downloadServer)) + Row() { Text($r('app.string.HFS_tips')) .textStyle() @@ -87,8 +93,21 @@ struct Index { this.CapabilityView($r('app.media.ic_download'), $r('app.string.download'), 'btn_download', () => { router.pushUrl({ url: 'pages/Download' + }) + }) + this.CapabilityView($r('app.media.ic_download'), $r('app.string.downloadToUser'), 'btn_downloadToUser', + () => { + if (this.isBackground == false ) { + router.pushUrl({ + url: 'pages/Download', + params: { + action: 'ToUser' + } + }) + } else { + promptAction.showToast({ message: '不支持后台下载到用户目录', duration: 5000 }); + } }) - }) this.CapabilityView($r('app.media.ic_certified'), $r('app.string.cert_lock'), 'btn_cert_lock', () => { router.pushUrl({ url: 'pages/CertLock' diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Upload.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Upload.ets index 33bb2eb4adad8c8e5493bfcba1eff8c30e5d6f67..d47bf2c71ac492adbf9290f384100b79ff223731 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Upload.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/ets/pages/Upload.ets @@ -168,7 +168,7 @@ struct Upload { this.progress = 0; let index = this.chunkImgIndex; let fileUris = this.imageList.slice(index); - console.debug(TAG + 'fileuri:' + fileUris); + logger.debug(TAG + 'fileuri:' + fileUris); requestUpload.uploadFileChunk(fileUris, this.chunkParaBegins, this.chunkParaEnds, (progress: number, isSucceed: boolean) => { this.progress = progress; if (this.progress === 100 && isSucceed) { @@ -191,7 +191,7 @@ struct Upload { }); return; } - console.debug(TAG + ':imageList:' + this.imageList); + logger.debug(TAG + ':imageList:' + this.imageList); if (this.isBackground) { AppStorage.setOrCreate('backTaskState', BackgroundTaskState.RUNNING); requestUpload.uploadFilesBackground(this.imageList); diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/base/element/string.json b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/base/element/string.json index f2f3603345c9a27a841d2e68c39898a5f00ad1d2..15f5c8c4107a8068047055cab00d3de6bbcbd02a 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/base/element/string.json +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/base/element/string.json @@ -68,6 +68,18 @@ "name": "download", "value": "Download" }, + { + "name": "downloadToApplication", + "value": "downloadToApplication" + }, + { + "name": "downloadToUser", + "value": "DownloadToUser" + }, + { + "name": "downloadServer", + "value": "https://gitee.com/tiga-ultraman/downloadTests/releases/download/v1.01/" + }, { "name": "download_to", "value": "Select a download location" diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/en_US/element/string.json b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/en_US/element/string.json index 751ab62d304e701efd05b5e01b206a67ef66f67c..ab355f1e970b4266db34061ebc2b5cee7fb35f7c 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/en_US/element/string.json +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/en_US/element/string.json @@ -139,6 +139,14 @@ { "name": "cert_lock", "value": "Cert lock" + }, + { + "name": "downloadToUser", + "value": "DownloadToUser" + }, + { + "name": "downloadToApplication", + "value": "DownloadToApplication" } ] } \ No newline at end of file diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/zh_CN/element/string.json b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/zh_CN/element/string.json index 94ea0de964e570fad3648c6e35964bb2f15a1e72..3e42b66c3fb38c550c6b1e150c122191e109761e 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/zh_CN/element/string.json +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/entry/src/main/resources/zh_CN/element/string.json @@ -139,6 +139,14 @@ { "name": "cert_lock", "value": "证书锁定" + }, + { + "name": "downloadToUser", + "value": "下载到用户目录" + }, + { + "name": "downloadToApplication", + "value": "下载到应用目录" } ] } \ No newline at end of file diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/components/FileBrowse.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/components/FileBrowse.ets index e8fd253d4cde3ad9e0a022cf7610d1d5add62ae5..c476c471683db4dd94b757c950b6f34b3743aaea 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/components/FileBrowse.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/components/FileBrowse.ets @@ -21,9 +21,10 @@ export struct FileBrowse { @State folders: Array = ['folder']; @State files: Array = []; @State currentFolder: string = ''; + @Link downloadDir: string; aboutToAppear() { - fileUtils.listFolders().then((folders: Array) => { + fileUtils.listFolders(this.downloadDir).then((folders: Array) => { this.folders = folders; }) } @@ -57,7 +58,7 @@ export struct FileBrowse { .onStateChange(async (isActivated: boolean) => { if (isActivated) { this.currentFolder = item; - this.files = await fileUtils.listFiles(item); + this.files = await fileUtils.listFiles(this.downloadDir,item); } }) } @@ -132,7 +133,7 @@ export struct FileBrowse { } .margin({ bottom: 24, top: 6 }) .onClick(() => { - fileUtils.clearFolder(this.currentFolder); + fileUtils.clearFolder(this.downloadDir,this.currentFolder); this.files = []; }) } diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/download/RequestDownload.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/download/RequestDownload.ets index 4c58ce38c62dbc61c13e7468a701277fd0721275..8e1f1051f33c8d131368658587e61af1d3a1ac1b 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/download/RequestDownload.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/download/RequestDownload.ets @@ -99,7 +99,7 @@ class RequestDownload { } async downloadFile(folder: string, url: string, callback: (progress: number, isSuccess: boolean) => void) { - logger.info(TAG, 'downloadFile'); + logger.info(TAG, `downloadFile folder:${folder} url:${url}`); // 查询到存在正在执行的下载任务,提示并返回 let tasks = await request.agent.search({ state: request.agent.State.RUNNING, @@ -111,15 +111,16 @@ class RequestDownload { return; } let splitUrl = url.split('//')[1].split('/'); + let saveas = `${folder}/${splitUrl[splitUrl.length-1]}` let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; let downloadConfig: request.agent.Config = { action: request.agent.Action.DOWNLOAD, url: url, - method: 'POST', + method: 'GET', title: 'download', mode: request.agent.Mode.FOREGROUND, network: request.agent.Network.ANY, - saveas: `./${folder}/${splitUrl[splitUrl.length-1]}`, + saveas: saveas, overwrite: true } logger.info(TAG, `downloadFile, downloadConfig = ${JSON.stringify(downloadConfig)}`); @@ -142,7 +143,8 @@ class RequestDownload { this.downloadTask.on('failed', async (progress: request.agent.Progress) => { if (this.downloadTask) { let taskInfo = await request.agent.show(this.downloadTask.tid); - logger.info(TAG, `fail, resean = ${taskInfo.reason}, faults = ${JSON.stringify(taskInfo.faults)}`); + logger.error(TAG, `fail, resean = ${taskInfo.reason}, faults = ${JSON.stringify(taskInfo.faults)}`); + promptAction.showToast({ message: `fail, resean = ${taskInfo.reason}, faults = ${JSON.stringify(taskInfo.faults)}`, bottom: TOAST_BOTTOM }); } callback(100, false); this.deleteTask(); @@ -150,6 +152,7 @@ class RequestDownload { await this.downloadTask.start(); } catch (err) { logger.error(TAG, `task err, err = ${JSON.stringify(err)}`); + promptAction.showToast({ message: JSON.stringify(err), bottom: TOAST_BOTTOM }); callback(100, false); } } diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/utils/FileUtils.ets b/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/utils/FileUtils.ets index 44e0ed2ac74492c9e52a8f6e2d98481fd0acd3c6..f97ad290bb8c8ee7b02abeeca9ce20aeb62d8129 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/utils/FileUtils.ets +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/features/uploadanddownload/src/main/ets/utils/FileUtils.ets @@ -24,41 +24,38 @@ class FileUtil { constructor() { } - async initDownloadDir(): Promise { - let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; - logger.info(TAG, `initDownloadDir cacheDir=${context.cacheDir}`); + async initDownloadDir(downloadDir: string): Promise { + logger.info(TAG, `initDownloadDir downloadDir=${downloadDir}`); try { - fs.mkdirSync(`${context.cacheDir}/${ALBUMS[0]}`); - fs.mkdirSync(`${context.cacheDir}/${ALBUMS[1]}`); - fs.mkdirSync(`${context.cacheDir}/${ALBUMS[2]}`); + fs.mkdirSync(`${downloadDir}/${ALBUMS[0]}`); + fs.mkdirSync(`${downloadDir}/${ALBUMS[1]}`); + fs.mkdirSync(`${downloadDir}/${ALBUMS[2]}`); } catch (err) { logger.info(TAG, `initDownloadDir err =${JSON.stringify(err)}`); } } - async listFolders(): Promise> { - await this.initDownloadDir(); + async listFolders(downloadDir: string): Promise> { + await this.initDownloadDir(downloadDir); return ALBUMS; } - async clearFolder(folderName: string): Promise { - let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + async clearFolder(downloadDir: string,folderName: string): Promise { try { - let files: string[] = fs.listFileSync(`${context.cacheDir}/${folderName}`); + let files: string[] = fs.listFileSync(`${downloadDir}/${folderName}`); logger.info(TAG, `listFiles listFileSync =${JSON.stringify(files)}`); for (let i = 0; i < files.length; i++) { - fs.unlinkSync(`${context.cacheDir}/${folderName}/${files[i]}`); + fs.unlinkSync(`${downloadDir}/${folderName}/${files[i]}`); } } catch (err) { logger.info(TAG, `listFiles err =${JSON.stringify(err)}`); } } - async listFiles(folderName: string): Promise> { - let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + async listFiles(downloadDir:string,folderName: string): Promise> { let files: string[] = []; try { - files = fs.listFileSync(`${context.cacheDir}/${folderName}`); + files = fs.listFileSync(`${downloadDir}/${folderName}`); logger.info(TAG, `listFiles listFileSync =${JSON.stringify(files)}`); } catch (err) { logger.info(TAG, `listFiles err =${JSON.stringify(err)}`); diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/oh-package.json5 b/code/BasicFeature/Connectivity/UploadAndDownLoad/oh-package.json5 index 5e3779b038dac86ae420dcbe71fac54bab468ab7..f301b514512bcc5b50d6f5c9137a9dd0eccc7568 100644 --- a/code/BasicFeature/Connectivity/UploadAndDownLoad/oh-package.json5 +++ b/code/BasicFeature/Connectivity/UploadAndDownLoad/oh-package.json5 @@ -14,6 +14,7 @@ */ { + "modelVersion": "5.0.5", "license": "", "devDependencies": { "@ohos/hypium": "1.0.6" diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/download_folder_user.jpg b/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/download_folder_user.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b76f9a7d8942e84f8d0fe734883e15cf2b27bfec Binary files /dev/null and b/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/download_folder_user.jpg differ diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/download_user.jpg b/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/download_user.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0035e0aca52877a90ea2ef6fe90d716daf599404 Binary files /dev/null and b/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/download_user.jpg differ diff --git a/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/home.jpg b/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/home.jpg index e19c858103eda3d17307bbed6d3a9558f8a780c9..8f143b1be64d7d3dd3d0cf5b48492582b18bc8a3 100644 Binary files a/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/home.jpg and b/code/BasicFeature/Connectivity/UploadAndDownLoad/screenshots/devices/zh/home.jpg differ