目录

Obtaining a File Icon

Use Cases

Obtain a file icon based on the file type.

API Description

API Description
getFileIconSync(fileType: string): string | Resource Obtains a file icon based on the file type.
getFileIcon(fileType: string): Promise<string | Resource> Obtains a file icon based on the file type. This API returns the result asynchronously through a promise.

Sample Code

  1. Import the File Manager Service Kit module and other related modules.
import { fileManagerService } from '@kit.FileManagerServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { uniformTypeDescriptor } from '@kit.ArkData';
  1. Request permissions. To use the API for obtaining file icons, you need to declare the required permission ohos.permission.GET_FILE_ICON in module.json5. For details, please refer to Declaring Permissions.

  2. Obtain a file icon.

@Component
export struct GetFileIcon {
  @State inputText: string = ''
  @State fileIcon: string | Resource = '';

  private getFileIconByFileExtension(filenameExtension: string): void {
    try {
      // Obtain the UTD-ID of the file type based on the file name extension.
      // filenameExtension indicates the file name extension. For example, for a .txt file, filenameExtension can be set to .txt.
      let typeId: string = uniformTypeDescriptor.getUniformDataTypeByFilenameExtension(filenameExtension);
      // Call getFileIconSync to obtain the file icon based on the UTD-ID.
      this.fileIcon = fileManagerService.getFileIconSync(typeId);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error('getFileIconByFileExtension failed with err: ' + JSON.stringify(err));
    }
  }

  build() {
    NavDestination() {
      Column() {
        Image(this.fileIcon)
          .height(88)
          .border({ width: 1, radius: 6 })

        TextInput({ placeholder: 'Enter the file name extension', text: $$this.inputText })
          .width('85%')
          .height(50)
          .borderRadius(8)
          .padding(12)

        Button('Obtain File Icon')
          .width('60%')
          .height(48)
          .type(ButtonType.Capsule)
          .onClick(() => {
            this.getFileIconByFileExtension(this.inputText);
          })
        Blank()
      }
      .width('100%')
      .height('100%')
      .backgroundColor(Color.White)
    }
    .width('100%')
    .height('100%')
  }
}