HarmonyOS 鸿蒙Next 保存图片权限请求问题

发布于 1周前 作者 vueper 最后一次编辑是 5天前 来自 鸿蒙OS

我需要将组件截图保存成文件。但是现在我在请求保存文件权限的时候失败了。我的代码是

async saveToFile() {

  try{

    let phAccessHelper:photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext())

    let srcFileUris:Array<string> = [

      'file://media/Photo/1/xxx/xxx.jpg'

    ]

    try{

      let photoCreationConfigs:Array<photoAccessHelper.PhotoCreationConfig> = [{

        fileNameExtension:'jpg',

        title:'xxx',

        photoType:photoAccessHelper.PhotoType.IMAGE

      }]

      console.info(`before show showAssetsCreationDialog ${srcFileUris.toString()} \n ${photoCreationConfigs.toString()} \n ${JSON.stringify(photoCreationConfigs)}`)

      let desFileUris:Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs)

      console.info('showAssetsCreationDialog success, data is ' + desFileUris)

      // this.saveFileWithUri(desFileUris[0])

    } catch (err) {

      console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);

    }

  } catch (err) {

    console.error('saveToFile failed, errCode is ' + err.code + ', errMsg is ' + err.message);

  }

}

运行会报错

showAssetsCreationDialog failed, errCode is 401, errMsg is input parmaeter invalid 现在的现象是,走到phAccessHelper.showAssetsCreationDialog方法后,就没有反应了,既没有成功的日志,也没有失败的日志,权限弹窗不弹出来。有人知道吗?


更多关于HarmonyOS 鸿蒙Next 保存图片权限请求问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

showAssetsCreationDialog中的srcFileUris应该是应用沙箱的图片/视频uri demo:

import { fileIo as fs, fileUri } from '@kit.CoreFileKit'

import { common } from '@kit.AbilityKit';

import { photoAccessHelper } from '@kit.MediaLibraryKit';

import { camera, cameraPicker as picker } from '@kit.CameraKit';

@Entry

@Component

struct Index {

  @State message: string = 'Hello World';

  async saveFile() {

    let mContext = getContext(this) as common.Context;

    let cameraType: number = 1;

    let types: Array<picker.PickerMediaType> = [picker.PickerMediaType.PHOTO];

    let pickerProfile: picker.PickerProfile = {

      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,

      videoDuration: 15

    };

    let pickerResult: picker.PickerResult = await picker.pick(mContext,

      types, pickerProfile);

    if (pickerResult.resultCode === 0) {

      // 成功

      let finalUri = pickerResult.resultUri;

      // 保存图片到缓存目录

      let dirpath = (getContext(this) as common.UIAbilityContext).tempDir + '/cameTem.jpg';

      let dirUri = fileUri.getUriFromPath(dirpath);

      let file = fs.openSync(pickerResult.resultUri, fs.OpenMode.READ_ONLY)

      let file2 = fs.openSync(dirpath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)

      fs.copyFileSync(file.fd, file2.fd)

      fs.closeSync(file);

      fs.closeSync(file2);

      console.info('ImagePicker', "Succeeded in copying. ");

      // 删除相册图片

      try {

        await photoAccessHelper.MediaAssetChangeRequest.deleteAssets(getContext(),

          [pickerResult.resultUri])

        finalUri = dirUri;

      } catch (err) {

        console.error('ImagePicker', `deleteAssetsDemo failed with error: ${err.code}, ${err.message}`);

      }

      console.info('ShowAssetsCreationDialogDemo.');

      try { // 获取需要保存到媒体库的位于应用沙箱的图片/视频uri

        let srcFileUris: Array<string> = [dirUri];

        let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [{

          // title: 'test2', // 可选

          fileNameExtension: 'jpg',

          photoType: photoAccessHelper.PhotoType.IMAGE,

          // subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选

        }];

        let context = getContext();

        let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);

        let desFileUris: Array<string> =

          await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);

        console.info('showAssetsCreationDialog success, data is ' + desFileUris);

        try {

          let file = fs.openSync(srcFileUris[0], fs.OpenMode.READ_ONLY)

          let file2 = fs.openSync(desFileUris[0], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)

          fs.copyFileSync(file.fd, file2.fd)

          fs.closeSync(file);

          fs.closeSync(file2);

        } catch (e) {

          console.log(JSON.stringify(e))

        }

      } catch (err) {

        console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);

      }

    }

  }

  build() {

    RelativeContainer() {

      Text(this.message)

        .id('HelloWorld')

        .fontSize(50)

        .fontWeight(FontWeight.Bold)

        .alignRules({

          center: { anchor: '__container__', align: VerticalAlign.Center },

          middle: { anchor: '__container__', align: HorizontalAlign.Center }

        })

        .onClick(() => {

          this.saveFile();

        })

    }

    .height('100%')

    .width('100%')

  }

}

更多关于HarmonyOS 鸿蒙Next 保存图片权限请求问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next系统中,保存图片权限请求的处理需遵循系统权限管理机制。

首先,确保在应用的manifest.json文件中已声明存储权限。对于图片保存,通常需要ohos.permission.WRITE_EXTERNAL_STORAGEohos.permission.READ_EXTERNAL_STORAGE权限。

"module": {
    "reqPermissions": [
        {
            "name": "ohos.permission.WRITE_EXTERNAL_STORAGE"
        },
        {
            "name": "ohos.permission.READ_EXTERNAL_STORAGE"
        }
    ]
}

在代码中,使用PermissionManager来请求权限。示例如下:

// 注意:此段代码为示例框架,实际代码需用鸿蒙API
PermissionManager permissionManager = PermissionManager.getInstance(this);
List<String> permissions = Arrays.asList("ohos.permission.WRITE_EXTERNAL_STORAGE", "ohos.permission.READ_EXTERNAL_STORAGE");

int[] results = permissionManager.requestPermissionsFromUser(new int[]{PermissionManager.PERMISSION_GRANT}, permissions, 0);

if (results.length > 0 && results[0] == PermissionManager.PERMISSION_GRANT) {
    // 权限已授予,执行保存图片操作
} else {
    // 权限未授予,处理相应逻辑
}

注意,上述代码中的API调用需根据HarmonyOS实际API进行调整,因鸿蒙系统API与Android存在差异。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部