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

通过系统相机拍照, 返回了一个照片的url信息, 具体信息如下: file://media/Photo/19/IMG_1721126033_009/IMG_20240716_183213.jpg

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

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

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%')
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 媒体文件 C++ 访问问题
77浏览 • 1回复 待解决
在读取媒体文件open: permission denied
2908浏览 • 1回复 待解决
文件上传本地路径如何获取
437浏览 • 1回复 待解决
如何获取应用自身文件路径
2110浏览 • 1回复 待解决
如何获取资源文件路径
1974浏览 • 1回复 待解决
鸿蒙如何获取资源文件路径
16521浏览 • 3回复 待解决
如何获取文件绝对路径
2210浏览 • 1回复 待解决
HarmonyOS AVSession如何获取媒体id?
218浏览 • 1回复 待解决
如何获取profile路径下资源文件
1830浏览 • 1回复 待解决