OpenHarmony开发者论坛

标题: OpenHarmony应用如何获取媒体文件的标准化数据类型及其图标文件 [打印本页]

作者: 深开鸿_张守忠    时间: 2023-12-13 15:07
标题: OpenHarmony应用如何获取媒体文件的标准化数据类型及其图标文件
[md]### 简介:

** 媒体文件如图片,音频,视频等类型文件的标准话数据类型获取可以使用@ohos.data.uniformTypeDescriptor。**

### 文档环境:

* **开发环境:Windows 10专业版**
* **DevEco Studio版本:DevEco Studio 4.0Release (4.0.0.600)**
* **SDK版本:4.1.3.3 (full sdk)**
* **API版本:Version 11**
* **开发板型号:DAYU200(RK3568)**
* **系统版本:OpenHarmony 4.1.3.5**

### 演示demo:

* **新建一个 Stage 框架的 demo 工程,在page/Index.ets中通过 let context = getContext(this) as common.UIAbilityContext;filePath = context.filesDir; 拿到应用的沙箱files路径信息,通过文件操作接口在files下创建文件夹utdType并分别创建以png,mp3,mp4为后缀的文件。**
* **通过接口fs.listFileSync(filesPath)获取utdType\_test文件夹下的所有文件,由字符串接口index = fileName.lastIndexOf('.')和fileExtension = fileName.substring(index)拿到文件的后缀。**
* **通过接口getUniformDataTypeByFilenameExtension(fileExtension)获得文件标准化数据类型,再通过接口getTypeDescriptor和belongsTo判断文件是否归属与标准化数据类型xxx** **demo运行效果:** ** **![image](file://D:/project/OpenHarmony_sample/sample_%E9%9C%80%E6%B1%82&%E8%AF%A6%E7%BB%86%E8%AE%BE%E8%AE%A1/UTDType_sample/screenshots/select_type.png?lastModify=1702451224) ** 核心代码如下:**

```
import utdDesc from '@ohos.data.uniformTypeDescriptor';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import hilog from '@ohos.hilog';

let context = getContext(this) as common.UIAbilityContext;
let baseDir = context.filesDir;
let filesPath = baseDir + '/utdType';

class FileInfo {
 filename: string;
 utdType: string;
 iconFile: string;

 constructor(fileName: string, utdType: string, iconFile: string) {
   this.filename = fileName;
    this.utdType = utdType;
   this.iconFile = iconFile;
  }
}

let class2UTD = new Map([
  ["Images", "general.image"],
  ["Audios", "general.audio"],
  ["Videos", "general.video"]
]);

let precastFiles: string[] = [
 "imagePng.png",
 "audioMp3.mp3",
 "videoMp4.mp4",
];

function CreatePrecastFile(): void {
 try {
   let res = fs.accessSync(filesPath);
   if (res) {
     hilog.info(0, `file path: ${filesPath} exists`);
   } else {
     hilog.info(0, `file path: ${filesPath} not exists`);
     fs.mkdirSync(filesPath);
   }
  } catch (error) {
   let err: BusinessError = error as BusinessError;
   hilog.error(0, "accessSync failed with error message: " + err.message + ", error code: " + err.code);
  }

 for (let i = 0; i < precastFiles.length; i++) {
   let fileName = filesPath + "/" + precastFiles;
   hilog.info(0, `The file name: ${fileName}`);
   try {
     let res = fs.accessSync(fileName);
     if (res) {
       hilog.info(0, `file: ${fileName} exists!.`);
     } else {
       hilog.info(0, `file: ${fileName} not exists, will create it!.`);
       let file = fs.openSync(fileName, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
       hilog.info(0, "file fd: " + file.fd);
       fs.closeSync(file);
     }
   } catch (error) {
     let err: BusinessError = error as BusinessError;
     hilog.error(0, "accessSync failed with error message: " + err.message + ", error code: " + err.code);
   }
  }
}

@Entry
@Component
struct selectMediaType {
 @State text: string = "Images";
 @State index: number = 1;
 @State space: number = 12;
 @State arrowPosition: ArrowPosition = ArrowPosition.END;
 @State fileNames: string[] = [];
 @State selectedFilesInfos: FileInfo[] = [];
 private routerBackUrl: string = 'pages/Index';
 private routerNextUrl: string = 'pages/displayMediaFile';

 getListFile(): string[] {
   let files = fs.listFileSync(filesPath);
   for (let i = 0; i < files.length; i++) {
     hilog.info(0, `The name of file: ${files}`);
   }
   return files;
  }

 UpdateSelectedFiles(): void {
   this.fileNames = this.getListFile();
   for (let i = this.selectedFilesInfos.length - 1; i >= 0; i--) {
     this.selectedFilesInfos.pop();
   }
   this.selectedFilesInfos = [];
   hilog.info(0, "selectText: " + this.text)
   for (let i = 0; i < this.fileNames.length; i++) {
     let fileName = this.fileNames;
     hilog.info(0, `fileNames file: ${fileName}`);
     let index = fileName.lastIndexOf('.');
     if (index < 0) {
       continue;
     } else {
       let fileExtension = fileName.substring(index);
       hilog.info(0, `fileNames file extension: ${fileExtension}`);
       let utd = utdDesc.getUniformDataTypeByFilenameExtension(fileExtension);
       try {
         if (utd != null) {
           let typeObj: utdDesc.TypeDescriptor = utdDesc.getTypeDescriptor(utd);
            let utdType: string = "";
            if (typeObj.belongsTo("general.image")) {
              utdType = "general.image"
              
            } else if (typeObj.belongsTo("general.audio")) {
              utdType = "general.audio"
            } else if (typeObj.belongsTo("general.video")) {
              utdType = "general.video"
            } else {
              continue;
            }
            hilog.info(0, `typeObj.belongsTo: ${fileName}, utdType: ${utdType}`);
            let fileInfo = new FileInfo(fileName, utdType, typeObj.iconFile);
            this.selectedFilesInfos.push(fileInfo);
         }
       }
       catch (e) {
         let error: BusinessError = e as BusinessError;
         hilog.error(0, `belongsTo throws an exception. code is ${error.code}, message is ${error.message} `);
       }
     }
   }
  }

 aboutToAppear() {
   CreatePrecastFile();
   this.UpdateSelectedFiles();
  }

 aboutToDisappear() {
   for (let i = this.selectedFilesInfos.length - 1; i >= 0; i--) {
     this.selectedFilesInfos.pop();
   }
  }

 build() {
   Column() {
     Column() {
       List({ space: 2, initialIndex: 0 }) {
         ForEach(this.selectedFilesInfos, (item: FileInfo, no: Number) => {
           ListItem() {
             Row() {
               Image(item.iconFile)
                 .id('imageBack')
                 .width(24)
                 .height(24)
                 .objectFit(ImageFit.Fill)
                 .alignSelf(ItemAlign.Auto)
                 .margin({ left: 12, right: 12 })
                Text(item.filename)
                  .fontSize(16)
                  .textAlign(TextAlign.Start)
                  .margin({ left: 12, right: 12 })
                  .fontWeight(500)
                  .id("textFilename_" + no)
                  .visibility(Visibility.Visible)
                Text(item.utdType)
                  .fontSize(16)
                  .textAlign(TextAlign.Start)
                  .margin({ left: 12, right: 12 })
                  .fontWeight(500)
                  .id("textFilename_" + no)
                  .visibility(Visibility.Visible)
             }
             .width('100%')
             .height(48)
             .alignItems(VerticalAlign.Center)
           }
           .id("listItem_" + no)
         })
       }
       .listDirection(Axis.Vertical)
       .scrollBar(BarState.Auto)
       .friction(0.6)
       .margin({ left: 12, right: 12 })
       .borderRadius(24)
       .edgeEffect(EdgeEffect.Spring)
       .backgroundColor(0xFFFFFF)
     }
     .width('100%')
     .height(680)
     .alignItems(HorizontalAlign.Start)
     .justifyContent(FlexAlign.Start)
   }
   .width('100%')
   .height('100%')
   .backgroundColor(#F1F3F5)
   .alignItems(HorizontalAlign.Start)
   .justifyContent(FlexAlign.Center)
  }
}
```

### sample仓地址:

**本功能的sample仓地址:**[https://gitee.com/openharmony/applications\_app\_samples/tree/master/code/BasicFeature/DataManagement/UDMF/UniformTypeDescriptor/UTDType](https://gitee.com/openharmony/ap ... eDescriptor/UTDType)
[/md]




欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/) Powered by Discuz! X3.5