HarmonyOS 如何把系统文件通过uri复制到指定目录中

现在App通过picker,拿到了系统图片的uri (举例file://media/Photo/6/IMG_1716190263_005/9b09f2f4e62741558d98d862d432166e(1).jpg)。

现在想要将这个图片,复制到App的私有目录(比如 /data/storage/el2/base/cache )下,请问该如何操作。

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

请参考以下demo

import picker from '@ohos.multimedia.cameraPicker'
import camera from '@ohos.multimedia.camera';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import fileuri from '@ohos.file.fileuri';
import fs from '@ohos.file.fs';
import photoAccessHelper from '@ohos.file.photoAccessHelper';

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


class CameraPosition {
  cameraPosition: camera.CameraPosition
  saveUri: string
  constructor(cameraPosition: camera.CameraPosition, saveUri: string) {
    this.cameraPosition = cameraPosition
    this.saveUri = saveUri
  }
}

let pathDir = getContext().filesDir;
console.log('保存路径为'+pathDir)
let filePath = pathDir + '/picture.jpg'
fs.createRandomAccessFileSync(filePath, fs.OpenMode.CREATE);
let uri = fileuri.getUriFromPath(filePath);
async function photo() {
  try {
    let pickerProfile = new CameraPosition(camera.CameraPosition.CAMERA_POSITION_BACK, uri)
    let pickerResult: picker.PickerResult = await picker.pick(context,
      [picker.PickerMediaType.PHOTO, picker.PickerMediaType.VIDEO], pickerProfile);
    console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
  } catch (error) {
    let err = error as BusinessError;
    console.error(`the pick call failed. error code: ${err.code}`);
  }
}
async function picture() {
  let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  PhotoSelectOptions.maxSelectNumber = 1;
  let photoPicker = new photoAccessHelper.PhotoViewPicker();
  photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
    let photouri: Array<string> = PhotoSelectResult.photoUris
    let file = fs.openSync(photouri[0], fs.OpenMode.READ_ONLY)
    let file2 = fs.openSync(pathDir+'/picture2.jpg', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    fs.copyFileSync(file.fd, file2.fd)
    fs.closeSync(file);
    fs.closeSync(file2);
  })
}


@Entry
@Component
export struct Index {
  build() {
    Column() {
      Button('选择并保存').onClick(() => {
        picture()
      })
      Button('拍照并保存').onClick(() => {
        photo()
      })
    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 文件复制到指定目录的demo
22浏览 • 1回复 待解决
HarmonyOS 怎么内容复制到剪切板
532浏览 • 1回复 待解决
如何将docker容器文件复制到主机?
2483浏览 • 1回复 待解决
如何将内容直接复制到剪贴板
657浏览 • 1回复 待解决
HarmonyOS 怎样将文本复制到粘贴板
72浏览 • 1回复 待解决
ubuntu复制512000*16个小文件硬盘
2066浏览 • 1回复 待解决
HarmonyOS rawfile文件如何获取URI
37浏览 • 1回复 待解决
HarmonyOS 下载文件并保存到指定目录
96浏览 • 1回复 待解决