HarmonyOS 如何将拍照获取到的文件拷贝到沙箱中?

context.startAbilityForResult({
  action:'ohos.want.action.imageCapture',
  parameters:{
    callBundleName:'com.hm.imageshow'
  }
}, async (err, data) => {
  if (err?.code === 0) {
    const uri = (data?.want?.parameters as Record<string, Object>)['resourceUri']?.toString();
    const fileName = getFileName(uri);
    const fileType = fileName.lastIndexOf('.') > -1 ? fileName.substring(fileName.lastIndexOf('.')) : '';
    const localId = `${dayjs().format('YYYYMMDDHHmmssSSS')}_${Global.getInstance().getPartIMEI()}${fileType}`;
    const saveDir = `${SYSTEM_DIRECTORY_CAMERA}files/`;
    const srcPath = uri.replace('file:/', '');
    const destPath = `${saveDir}${localId}`;
    if (!isFileExist(saveDir)) {
      fs.mkdirSync(saveDir, true);
    }
    if (isSaveToAlbum) {
      fs.copyFileSync(srcPath, destPath, 0);
    } else {
      fs.moveFileSync(srcPath, destPath, 0);
    }

拍照或者选择照片获取到的路径为file://,无法拷贝到沙箱中,调用copyFileSync,moveFileSync均报错,如何解决

阅读 419
1 个回答

看下下面这个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 = 2;
  let photoPicker = new photoAccessHelper.PhotoViewPicker();
  photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
    let photouri: Array<string> = PhotoSelectResult.photoUris
    console.log("photouri" + JSON.stringify(photouri))
    console.log('保存路径为' + pathDir)
    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
struct SaveImage2Sanbox {
  @State message: string = 'Hello World';

  build() {
    Column() {
      Button('选择并保存')
        .onClick(() => {
          picture()
        })
      Button('拍照并保存')
        .onClick(() => {
          photo()
        })
      Button('删除')
        .onClick(() => {
          fs.unlinkSync(pathDir)
          fs.rmdirSync(pathDir)
        })
    }
    .height('100%')
    .width('100%')
  }
}

fs.moveFileSync的用法:

其中srcPath 是:源文件的应用沙箱路径,destPath 是:目的文件的应用沙箱路径。

let srcPath = pathDir + "/source.txt";
let destPath = pathDir + "/dest.txt";
fs.moveFileSync(srcPath, destPath, 0);
console.info("move file succeed");
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏