HarmonyOS 鸿蒙Next 读取路径文件资源

发布于 1周前 作者 bupafengyu 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 读取路径文件资源 现在有一个需求就是 做混合开发 h5页面给我传过来一个资源文件路径 我需要用原生能力去读取文件并且转换成base64返回 这里有可以直接去读取 这个路径文件的 api嘛 看文档中的file.fs 都是读沙盒中 ,但是这个文件怎么存到沙盒中呢?

10 回复

h5页面传过来的资源文件路径大概是什么样的,是图库的吗,还是download,可以参考一下图库这边的转换,对一下路径

import photoAccessHelper from '@ohos.file.photoAccessHelper';
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';

@Entry
@Component
struct Page2 {
  @State resultBase64Str: string = '';
  @State getAlbum: string = '显示相册中的图片';
  @State pixel: image.PixelMap | undefined = undefined;
  @State albumPath: string = '';
  @State photoSize: number = 0;

  async getPictureFromAlbum() {
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
    this.albumPath = photoSelectResult.photoUris[0];
    console.info('albumPath: ' + this.albumPath)
    const file = fs.openSync(this.albumPath, fs.OpenMode.READ_WRITE);
    this.photoSize = fs.statSync(file.fd).size;
    console.info('Photo Size: ' + this.photoSize);
    let buffer1 = new ArrayBuffer(this.photoSize);
    fs.readSync(file.fd, buffer1);
    let base64Str: string = buffer.from(buffer1).toString('base64')
    let resultBase64Str = "data:image/png;base64," + base64Str
    this.resultBase64Str = resultBase64Str
    fs.closeSync(file);
    const imageSource = image.createImageSource(buffer1);
    console.log('imageSource: ' + JSON.stringify(imageSource));
    this.pixel = await imageSource.createPixelMap({});
  }

  build() {
    Scroll() {
      Column() {
        Text('获取图片')
          .onClick(async () => {
            await this.getPictureFromAlbum()
          })
        Image(this.resultBase64Str).width(40).height(40)

        Text(this.resultBase64Str)
      }
    }
  }
}

更多关于HarmonyOS 鸿蒙Next 读取路径文件资源的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


跑到这里就死掉了。我查的结果是这个 URI 没有权限被 fs 读取。您知道怎么解决这个问题嘛?

你的ide和样机是什么版本的呀

都是最新的啊,

基本信息

  • 项目名称: 示例项目
  • 作者: 张三
  • 版本: 1.0.0
  • 描述: 这是一个示例描述。

联系信息

/**

  • 保存文件
  • @param dirPath
  • @param fileName
  • @param buf */ writeBufferToFile(dirPath: string, fileName: string, buf: ArrayBuffer) { if (!fs.accessSync(dirPath)) { // 如果文件夹不存在,则先创建文件夹 fs.mkdirSync(dirPath) }

let file = fs.openSync(${dirPath}/${fileName}, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(file.fd, buf) fs.closeSync(file) }

/**

  • 读取文件内容
  • @param filePath 文件路径
  • @returns 文件内容 */ readContentFromFile(filePath: string): string { let result = ‘’ if (fs.accessSync(filePath)) { let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY) let bufSize = 4096 let readSize = 0 let buf = new ArrayBuffer(bufSize) let readOptions: ReadOptions = { offset: readSize, length: bufSize } let readLen = fs.readSync(file.fd, buf, readOptions) result = util.TextDecoder.create(‘utf-8’).decodeWithStream(new Uint8Array(buf)) while (readLen > 0) { readSize += readLen readOptions.offset = readSize readLen = fs.readSync(file.fd, buf, readOptions) result += util.TextDecoder.create(‘utf-8’).decodeWithStream(new Uint8Array(buf)) } fs.closeSync(file) } return result }

/**

  • 将内容写入文件
  • @param dirPath 文件及路径
  • @param fileName 文件名称
  • @param content 内容 */ function writeContentToFile(dirPath: string, fileName: string, content: string) { if (!fs.accessSync(dirPath)) { // 如果文件夹不存在,则先创建文件夹 fs.mkdirSync(dirPath) }

let file = fs.openSync(${dirPath}/${fileName}, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) fs.writeSync(file.fd, content) fs.closeSync(file) }

我现在做到了就是那个获取的路径就是手机本地内部的路径 但是我 let file = fs.openSync(${dirPath}/${fileName}, fs.OpenMode.READ_WRITE | 走这步的时候 打断点 file是undifind

这个问题属于访问沙盒的bug了,这个月中旬貌似鸿蒙那边会修复。

在HarmonyOS(鸿蒙Next)中,读取路径文件资源可以通过使用ohos.file.fs模块中的API来实现。具体步骤如下:

  1. 获取文件路径:首先需要确定要读取的文件路径。可以使用context.getFilesDir()获取应用内部存储的文件目录,或者使用context.getExternalFilesDir()获取外部存储的文件目录。

  2. 打开文件:使用fs.openSync()方法打开文件,该方法返回一个文件描述符(File Descriptor),用于后续的读写操作。

  3. 读取文件内容:使用fs.readSync()方法读取文件内容。该方法需要传入文件描述符、读取的缓冲区、读取的起始位置和读取的字节数。

  4. 关闭文件:读取完成后,使用fs.closeSync()方法关闭文件,释放资源。

以下是一个简单的代码示例:

import fs from '@ohos.file.fs';
import featureAbility from '@ohos.ability.featureAbility';

let context = featureAbility.getContext();
let filePath = context.getFilesDir() + '/example.txt';

let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let buffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, buffer, { offset: 0, length: buffer.byteLength });
let content = String.fromCharCode.apply(null, new Uint8Array(buffer, 0, readLen));
fs.closeSync(file.fd);

在这个示例中,首先获取了应用内部存储的文件路径,然后打开文件并读取内容,最后关闭文件。读取的内容存储在content变量中。

在HarmonyOS(鸿蒙Next)中,读取路径文件资源可以通过ResourceManager类实现。首先,获取ResourceManager实例,然后使用getRawFilegetRawFileEntry方法读取指定路径的文件资源。例如:

ResourceManager resourceManager = getResourceManager();
try {
    RawFileEntry rawFileEntry = resourceManager.getRawFileEntry("resources/rawfile/myfile.txt");
    InputStream inputStream = rawFileEntry.openRawFile();
    // 处理输入流
} catch (IOException e) {
    e.printStackTrace();
}

确保文件路径正确,并处理可能的异常。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!