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均报错,如何解决

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

看下下面这个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");
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 沙箱文件拷贝
57浏览 • 1回复 待解决
如何将docker容器文件复制主机?
2483浏览 • 1回复 待解决
如何将cookie同步web
587浏览 • 1回复 待解决
HarmonyOS 如何将PixelMap保存为沙箱
40浏览 • 1回复 待解决
如何将PixelMap数据存储数据库
1898浏览 • 1回复 待解决
如何将鸿蒙操作系统移植orange pi
651浏览 • 1回复 待解决