HarmonyOS 获取媒体文件的具体路径?

通过系统相机拍照, 返回了一个照片的url信息, 具体信息如下: file://media/Photo/19/IMG\_1721126033\_009/IMG\_20240716\_183213.jpg

目前我们应用的需求的拍照后需要将该图片源文件上传自服务器, 请问如何获取到该资源uri 在手机上面的具体path路径?

阅读 449
1 个回答

filePath需要转换为沙箱文件路径,文件操作转换参考

https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-local-file-manager-1-V5

参考代码如下:

let uris: Array<string> = [];
const photoViewPicker = new picker.PhotoViewPicker();
const photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
  uris = photoSelectResult.photoUris;
  console.info(‘photoViewPicker.select to file succeed and uris are:’ + uris);
  let file = fs.openSync(uris[0], fs.OpenMode.READ_ONLY);

  let file2 = fs.openSync(this.filesDir + ‘/test.jpg’, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);//先创建有读写权限的文件,再把不可读写的文件复制过来
  fs.copyFileSync(file.fd, file2.fd);
  // 关闭文件
  fs.closeSync(file);
  fs.closeSync(file2);

}).catch((err: BusinessError) => {
  console.error(Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message});
})

请开发者尝试转换path为应用的沙箱路径后再上传图片

以下是完整的通过PhotoViewPicker获取到的图片,通过将其复制在应用沙箱路径下,然后再用沙箱路径下的文件进行传输demo:

import { BusinessError } from '@ohos.base';
import { rcp } from '@kit.RemoteCommunicationKit';
import { picker } from '@kit.CoreFileKit';
import fs from '@ohos.file.fs';
import { http } from '@kit.NetworkKit';
let uploadUrl: string = 'http://huawei.com';

function example01(): string {
  let uri = '';
  let photoViewPicker = new picker.PhotoViewPicker();
  let photoSelectOption = new picker.PhotoSelectOptions();
  photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  photoViewPicker.select(photoSelectOption).then((photoSelectResult) => {
    console.log("photoSelectResult:" + photoSelectResult);
    uri = photoSelectResult.photoUris[0];
    console.log("uri:" + uri);
    try {
      let resultPhoto = fs.openSync(uri,fs.OpenMode.READ_ONLY);
      let resultName = resultPhoto.name;
      let fileTemp = fs.openSync(getContext().filesDir+resultPhoto.name,fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE);
      let imageUri = fileTemp.path;
      fs.copyFileSync(resultPhoto.fd,fileTemp.fd);
      fs.closeSync(resultPhoto);
      fs.closeSync(fileTemp);
      const httpRequest = http.createHttp();
      httpRequest.request(uploadUrl,{
        method:http.RequestMethod.POST,
        header:{
          'Content-Type': 'multipart/form-data',
          'Connection':'keep-alive'
        },
        expectDataType:http.HttpDataType.ARRAY_BUFFER,
        multiFormDataList: [
          {
            name:'file',
            contentType: 'image/jpg',
            filePath: imageUri,
            remoteFileName:'file.jpg'
          },
        ],
      },(err,data) => {
        console.log('上传结束')
        httpRequest.destroy();
      }
      )
    } catch (err) {
      console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
    }

  }).catch((err:BusinessError) => {
    console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  })
  return uri;
}
function testRcpMultiPartUpload() {
  example01();
}
function clickget() {
  const session = rcp.createSession();
  session.get("http://huawei.com").then((response) => {
    console.log(JSON.stringify(response));
  }).catch((err: BusinessError) => {
    console.error("err:" + JSON.stringify(err));
  });
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            testRcpMultiPartUpload();
          })
        Text('getText')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            clickget();
          })

      }
      .width('100%')
    }
    .height('100%')
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏