目录

Sharing Images

Image sharing allows users to share one or more images to the target device or app.

Development Procedure

  1. Import required modules.

    import { systemShare } from '@kit.ShareKit';
    import { uniformTypeDescriptor as utd } from '@kit.ArkData';
    import { common } from '@kit.AbilityKit';
    import { fileUri } from '@kit.CoreFileKit';
    import { BusinessError } from '@kit.BasicServicesKit';
  2. Construct the data to be shared.

    // Construct ShareData. You need to configure a valid data record.
    let uiContext: UIContext = this.getUIContext();
    let contextFaker: Context = uiContext.getHostContext() as Context;
    let filePath = contextFaker.filesDir + '/exampleImage.jpg'; // This is only an example. Replace it with the correct file path.
    // Obtain the precise UTD type.
    let utdTypeId = utd.getUniformDataTypeByFilenameExtension('.jpg', utd.UniformDataType.IMAGE);
    let shareData: systemShare.SharedData = new systemShare.SharedData({
      utd: utdTypeId,
      uri: fileUri.getUriFromPath(filePath),
      title: 'Image title', // If this parameter is not passed, the image file name will be displayed.
      description: 'Image description', // If this parameter is not passed, the image size will be displayed.
      // thumbnail: new Uint8Array() // You are advised to pass a suitable thumbnail for preview. If no thumbnail is passed, the original image will be used as the preview image by default.
    });

    You can use the fileUri.getUriFromPath method to obtain the file URI from the sandbox path.

  3. Add a record.

    shareData.addRecord({
      utd: utdTypeId,
      uri: fileUri.getUriFromPath(filePath),
      title: 'Image title', // If this parameter is not passed, the image file name will be displayed.
      description: 'Image description' // If this parameter is not passed, the image size will be displayed.
    });
  4. Start the sharing panel.

    // Display the sharing panel.
    let controller: systemShare.ShareController = new systemShare.ShareController(shareData);
    let context: common.UIAbilityContext = uiContext.getHostContext() as common.UIAbilityContext;
    controller.show(context, {
      selectionMode: systemShare.SelectionMode.SINGLE,
      previewMode: systemShare.SharePreviewMode.DETAIL
    }).then(() => {
      console.info('ShareController show success.');
    }).catch((error: BusinessError) => {
      console.error(`ShareController show error. code: ${error.code}, message: ${error.message}`);
    });

    For details about the complete sample code, please refer to Sample Code - Sharing Images.