medialibrary-filepath-guidelines.md 11.3 KB
Newer Older
G
Gloria 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# File Path Management

User data on OpenHarmony is managed by the **mediaLibrary** module in a unified manner. You can use the APIs provided by this module to access and operate the user data.

> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.

To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).

## File Formats Supported by Public Directories

Before using file paths for development, learn the file formats supported by each public directory.
> **CAUTION**
>
> The following table lists only the file types that can be identified by the system. In your application development, pay attention to the file formats supported by the corresponding interfaces. <br> For example, only .jpeg and .webp can be used for image encoding, and only .jpg, .png, .gif, .bmp, .webp, and .raw can be used for image decoding.

| Directory  | Directory Type     | Media Type     | Description          | Supported File Format                                              |
| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ |
20
| Camera/    | DIR_CAMERA    |    VIDEO and   IMAGE      | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
G
Gloria 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| Videos/    | DIR_VIDEO     | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv                     |
| Pictures/  | DIR_IMAGE     | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif |
| Audios/    | DIR_AUDIO     | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg                                    |
| Documents/ | DIR_DOCUMENTS | FILE  |Dedicated file directory. Only files except audios, images, and videos can be stored in this directory and its subdirectories.| -                                                |
| Download/  | DIR_DOWNLOAD  | ALLTYPE       |Directory for storing downloaded files. The types of files in this directory and its subdirectories are not restricted.| -                                                    |

## Obtaining a Public Directory

Different types of files are stored in different public directories. You can call [getPublicDirectory](../reference/apis/js-apis-medialibrary.md#getpublicdirectory8-1) to obtain the public directory that stores files of a certain type.

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.

The following describes how to obtain the public directory that stores camera files.

```ts
async function example(){
G
Gloria 已提交
40 41 42 43 44 45 46 47 48
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
  const dicResult = await media.getPublicDirectory(DIR_CAMERA);
  if (dicResult == 'Camera/') {
    console.info('mediaLibraryTest : getPublicDirectory passed');
  } else {
    console.error('mediaLibraryTest : getPublicDirectory failed');
  }
G
Gloria 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61
}
```

## Copying Files Between the Application Sandbox and the Public Directory

OpenHarmony provides the application sandbox to minimize the leakage of application data and user privacy information.

Users can access files stored in the public directories through the system applications **Files** and **Gallery**. However, files in the application sandbox can be accessed only by the application itself.

### Copying a File

You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.

G
Gloria 已提交
62
You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
G
Gloria 已提交
63 64 65 66

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
G
Gloria 已提交
67 68 69
- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
- The **testFile.txt** file has been created and contains content.
G
Gloria 已提交
70 71 72

**How to Develop**

G
Gloria 已提交
73
1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox.
G
Gloria 已提交
74
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
G
Gloria 已提交
75
3. Call **fs.open** to open the file in the sandbox.
G
Gloria 已提交
76
4. Call **fileAsset.open** to open the file in the public directory.
G
Gloria 已提交
77 78
5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file.
6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file.
G
Gloria 已提交
79 80 81 82 83

**Example 1: Copying Files from the Public Directory to the Sandbox**

```ts
async function copyPublic2Sandbox() {
G
Gloria 已提交
84
  try {
G
Gloria 已提交
85
    const context = getContext(this);
86
    let media = mediaLibrary.getMediaLibrary(context);
G
Gloria 已提交
87
    let sandboxDirPath = context.filesDir;
88
    let fileKeyObj = mediaLibrary.FileKey;
G
Gloria 已提交
89
    let fileAssetFetchOp = {
G
Gloria 已提交
90 91
      selections: fileKeyObj.DISPLAY_NAME + '= ?',
      selectionArgs: ['testFile.txt'],
G
Gloria 已提交
92 93 94 95 96
    };
    let fetchResult = await media.getFileAssets(fileAssetFetchOp);
    let fileAsset = await fetchResult.getFirstObject();

    let fdPub = await fileAsset.open('rw');
G
Gloria 已提交
97 98
    let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    await fs.copyFile(fdPub, fdSand.fd);
G
Gloria 已提交
99 100

    await fileAsset.close(fdPub);
G
Gloria 已提交
101
    await fs.close(fdSand.fd);
G
Gloria 已提交
102

G
Gloria 已提交
103 104 105 106 107
    let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt');
    console.info('content read from sandbox file: ', content_sand)
  } catch (err) {
    console.info('[demo] copyPublic2Sandbox fail, err: ', err);
  }
G
Gloria 已提交
108 109 110 111 112 113 114
}
```

**Example 2: Copying a File from the Sandbox to the Public Directory**

```ts
async function copySandbox2Public() {
G
Gloria 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  let sandboxDirPath = context.filesDir;

  let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
  const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
  try {
    let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
    console.info('createFile successfully, message = ' + fileAsset);
  } catch (err) {
    console.error('createFile failed, message = ' + err);
  }
  try {
    let fileKeyObj = mediaLibrary.FileKey;
    let fileAssetFetchOp = {
      selections: fileKeyObj.DISPLAY_NAME + '= ?',
      selectionArgs: ['testFile02.txt'],
    };
    let fetchResult = await media.getFileAssets(fileAssetFetchOp);
    var fileAsset = await fetchResult.getFirstObject();
  } catch (err) {
    console.error('file asset get failed, message = ' + err);
  }
  let fdPub = await fileAsset.open('rw');
  let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE);
  await fs.copyFile(fdSand.fd, fdPub);
  await fileAsset.close(fdPub);
  await fs.close(fdSand.fd);
  let fdPubRead = await fileAsset.open('rw');
  try {
    let arrayBuffer = new ArrayBuffer(4096);
    await fs.read(fdPubRead, arrayBuffer);
    var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
    fileAsset.close(fdPubRead);
  } catch (err) {
    console.error('read text failed, message = ', err);
  }
  console.info('content read from public file: ', content_pub);
G
Gloria 已提交
153 154 155 156 157
}
```

### Reading and Writing a File

G
Gloria 已提交
158
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file.
G
Gloria 已提交
159 160 161 162

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
G
Gloria 已提交
163 164
- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
G
Gloria 已提交
165 166 167 168 169

**How to Develop**

1. Create a file.

G
Gloria 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183
```ts
async function example() {
  let mediaType = mediaLibrary.MediaType.FILE;
  let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const path = await media.getPublicDirectory(DIR_DOCUMENTS);
  media.createAsset(mediaType, "testFile.text", path).then((asset) => {
    console.info("createAsset successfully:" + JSON.stringify(asset));
  }).catch((err) => {
    console.error("createAsset failed with error: " + err);
  });
}
```
G
Gloria 已提交
184 185 186

2. Call **FileAsset.open** to open the file.

G
Gloria 已提交
187
3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file.
G
Gloria 已提交
188

G
Gloria 已提交
189
4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer.
G
Gloria 已提交
190 191 192 193 194 195 196 197 198

5. Convert the array buffer to a string.

6. Use **FileAsset.close** to close the file.

**Example 1: Opening an Existing File and Writing Data to It**

```ts
async function writeOnlyPromise() {
G
Gloria 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  let fileKeyObj = mediaLibrary.FileKey;
  let fileAssetFetchOp = {
    selections: fileKeyObj.DISPLAY_NAME + '= ?',
    selectionArgs: ['testFile.txt'],
  };
  let fetchResult = await media.getFileAssets(fileAssetFetchOp);
  let fileAsset = await fetchResult.getFirstObject();
  console.info('fileAssetName: ', fileAsset.displayName);

  try {
    let fd = await fileAsset.open('w');
    console.info('file descriptor: ', fd);
    await fs.write(fd, "Write file test content.");
    await fileAsset.close(fd);
  } catch (err) {
    console.error('write file failed, message = ', err);
  }
G
Gloria 已提交
218 219 220 221 222 223 224
}
```

**Example 2: Opening an Existing File and Reading Data from It**

```ts
async function readOnlyPromise() {
G
Gloria 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  let fileKeyObj = mediaLibrary.FileKey;
  let fileAssetFetchOp = {
    selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
    selectionArgs: ['testFile.txt'],
  };
  let fetchResult = await media.getFileAssets(fileAssetFetchOp);
  let fileAsset = await fetchResult.getFirstObject();
  console.info('fileAssetName: ', fileAsset.displayName);

  try {
    let fd = await fileAsset.open('r');
    let arrayBuffer = new ArrayBuffer(4096);
    await fs.read(fd, arrayBuffer);
    let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
    globalThis.fileContent = fileContent;
    globalThis.fileName = fileAsset.displayName;
    console.info('file content: ', fileContent);
    await fileAsset.close(fd);
  } catch (err) {
    console.error('read file failed, message = ', err);
  }
G
Gloria 已提交
248 249
}
```