1# User File URI 2 3As a unique identifier of a user file, the uniform resource identifier (URI) is usually used to specify the user file to be accessed or modified. Avoid using part of an URI for service code development. 4 5## URI Types 6 7The URIs in the system can be classified into the following types: 8 9- Document URI: URI of a file selected or saved by the file manager started by picker, or obtained via the **fileAccess** module. For details, see [Obtaining a Document URI](#obtaining-a-document-uri). 10- Media file URI: URI of an image or video selected from **Gallery** by picker ; URI of an image or video obtained via the **photoAccessHelper** module; URI of an image, video, or audio file obtained via the **userFileManager** module. For details, see [Obtaining a Media File URI](#obtaining-a-media-file-uri). 11 12 13 14## Document URI 15 16### Document URI Overview 17 18The document URIs are in the following format: 19 20'file://docs/storage/Users/currentUser/\<relative_path\>/test.txt' 21 22The following table describes the fields in a document URI. 23 24| URI Field | Description | 25| ------------- | ------------------- | 26| 'file://docs/storage/Users/currentUser/' | Indicates the root directory of the file manager.| 27| '\<relative_path\>/' | Indicates the relative path of the file, for example, **Download/** and **Documents/**.| 28| 'test.txt' | Indicates the name of the file in the user file system. The supported file types vary with the file manager, for example, TXT, JPG, MP4, and MP3.| 29 30### Obtaining a Document URI 31 32- Use **select()** or **save()** of [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) to select or save a document. 33- Use **select()** or **save()** of [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) to select or save an audio file. 34- Use [PhotoViewPicker.save](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated) to save an image or video. The URI of the image or video saved is returned.<!--Del--> 35- Use [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md). The [FileInfo](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#fileinfo) object contains the URI of the file or directory. Note that the APIs of [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) can be called only by a system application. 36 37You can obtain the document URIs of the files and folders in the following directories: 38 39- External storage directory 40- **Docs** directory 41- **Download** directory 42- **Desktop** directory 43- **Documents** directory 44- **Share** directory of the shared disk 45<!--DelEnd--> 46 47### Using a Document URI 48 49Applications of the normal APL can call [@ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) APIs only to access files based on document URIs. "Permission denied" will be reported if an API of other modules is used. For details about the sample code, see [Selecting Documents](./select-user-file.md#selecting-documents) and [Saving Documents](./save-user-file.md#saving-documents).<!--Del--> 50 51Applications of the system_basic or system_core APL can call **@ohos.file.fs** and [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) APIs to access files based on the URIs. To call **@ohos.file.fileAccess** APIs, the application must have the ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permissions declared in **module.json5** file. "Permission denied" will be reported if an API of other modules is used. The following example walks you through on how to use **@ohos.file.fileAccess** APIs to create a document and rename the document based on the URI. 52 531. Use [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) to create a document. The document URI is returned. 542. Rename the document based on its URI. 55 56 ```ts 57 import { BusinessError } from '@kit.BasicServicesKit'; 58 import { Want } from '@kit.AbilityKit'; 59 import { common } from '@kit.AbilityKit'; 60 import { fileAccess } from '@kit.CoreFileKit'; 61 // context is passed by EntryAbility. 62 let context = getContext(this) as common.UIAbilityContext; 63 64 async function example() { 65 let fileAccessHelper: fileAccess.FileAccessHelper; 66 // Obtain wantInfos by using getFileAccessAbilityInfo(). 67 let wantInfos: Array<Want> = [ 68 { 69 bundleName: "com.ohos.UserFile.ExternalFileManager", 70 abilityName: "FileExtensionAbility", 71 }, 72 ] 73 try { 74 fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos); 75 if (!fileAccessHelper) { 76 console.error("createFileAccessHelper interface returns an undefined object"); 77 } 78 // A built-in storage directory is used as an example. 79 // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. 80 // Use the URI obtained. 81 let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; 82 let displayName: string = "file1.txt"; 83 let fileUri: string; 84 try { 85 // Create a document. The URI of the document created is returned. 86 fileUri = await fileAccessHelper.createFile(sourceUri, displayName); 87 if (!fileUri) { 88 console.error("createFile return undefined object"); 89 } 90 console.log("createFile success, fileUri: " + JSON.stringify(fileUri)); 91 // Rename the document. The URI of the renamed document is returned. 92 let renameUri = await fileAccessHelper.rename(fileUri, "renameFile.txt"); 93 console.log("rename success, renameUri: " + JSON.stringify(renameUri)); 94 } catch (err) { 95 let error: BusinessError = err as BusinessError; 96 console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); 97 } 98 } catch (err) { 99 let error: BusinessError = err as BusinessError; 100 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); 101 } 102 } 103 ``` 104 105<!--DelEnd--> 106 107## Media File URI 108 109### Media File URI Overview 110 111The URI format varies depending on the media file type. 112 113- Image URI format: 114 115 'file://media/Photo/\<id\>/IMG_datetime_0001/displayName.jpg' 116 117- Video URI format: 118 119 'file://media/Photo/\<id>/VID_datetime_0001/displayName.mp4' 120 121- Audio file URI format: 122 123 'file://media/Audio/\<id>/AUD_datetime_0001/displayName.mp3' 124 125The following table describes the fields in a media file URI. 126 127| URI Field | Description | 128| ------------- | ------------------- | 129| 'file://media' | Indicates a URI of a media file.| 130| 'Photo' | Indicates a URI of an image or video.| 131| 'Audio' | Indicates a URI of an audio file.| 132| '\<id>' | Indicates the ID of the file after being processed in multiple tables in the database. It is not the value in the **file_id** column in the table. Do not use this ID to query a file in the database.| 133| 'IMG_datetime_0001' | Indicates the name of the image stored in the user file system without the file name extension.| 134| 'VID_datetime_0001' | Indicates the name of the video stored in the user file system without the file name extension.| 135| 'AUD_datetime_0001' | Indicates the name of the audio file stored in the user file system without the file name extension.| 136|<!--DelRow--> 'displayName.jpg' | Indicates the image name displayed. You can use [userFileManager.commitModify](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#commitmodify) to rename it. Note that the URI of the new image name is also changed.| 137|<!--DelRow--> 'displayName.mp4' | Indicates the video name displayed. You can use [userFileManager.commitModify](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#commitmodify) to rename it. Note that the URI of the new video name is also changed.| 138|<!--DelRow--> 'displayName.mp3' | Indicates the audio file name displayed. You can use [userFileManager.commitModify](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#commitmodify) to rename it. Note that the URI of the new audio name is also changed.| 139 140### Obtaining a Media File URI 141 142- Use [PhotoViewPicker.select](../reference/apis-core-file-kit/js-apis-file-picker.md#select) to select a media file. 143 144- Use [getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) or [createAsset](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#createasset) of [photoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md).<!--Del--> 145 146- Use [getPhotoAssets](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#getphotoassets), [getAudioAssets](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#getaudioassets), [createAudioAsset](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#createaudioasset10), or [createPhotoAsset](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#createphotoasset) of [userFileManager](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md). 147 <!--DelEnd--> 148 149### Using a Media File URI 150 151Applications of the normal APL can call [photoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md) APIs to process media files based on their URI. For details about the sample code, see [Obtaining an Image or Video by URI](../media/medialibrary/photoAccessHelper-photoviewpicker.md#obtaining-an-image-or-video-by-uri). To call the APIs, the application must have the ohos.permission.READ_IMAGEVIDEO permission.<!--Del--> 152 153Applications of the system_basic or system_core APL can call **photoAccessHelper** and [userFileManager](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md) APIs to process media files based on their URI. For details about how to use the APIs, see the API reference document. 154<!--DelEnd--> 155 156Without the ohos.permission.READ_IMAGEVIDEO permission, the application of the normal APL can use [PhotoViewPicker.select](../reference/apis-core-file-kit/js-apis-file-picker.md#selectdeprecated-1) to obtain the URI, and use [photoAccessHelper.getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) to obtain the **PhotoAsset** object corresponding to the URI. The **PhotoAsset** object can be used to call [getThumbnail](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getthumbnail) to obtain the thumbnail and call [get](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#get) to read certain information in [PhotoKeys](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photokeys). 157 158The following information can be obtained from **PhotoKeys** through temporary authorization: 159 160| Name | Value | Description | 161| ------------- | ------------------- | ---------------------------------------------------------- | 162| URI | 'uri' | URI of the file. | 163| PHOTO_TYPE | 'media_type' | Type of the media file. | 164| DISPLAY_NAME | 'display_name' | File name displayed. | 165| SIZE | 'size' | Size of the file. | 166| DATE_ADDED | 'date_added' | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | 167| DATE_MODIFIED | 'date_modified' | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| 168| DURATION | 'duration' | Duration, in ms. | 169| WIDTH | 'width' | Image width, in pixels. | 170| HEIGHT | 'height' | Image height, in pixels. | 171| DATE_TAKEN | 'date_taken' | Date when the photo was taken. The value is the number of seconds elapsed since the Epoch time. | 172| ORIENTATION | 'orientation' | Orientation of the image file. | 173| TITLE | 'title' | Title in the file. | 174 175The following example shows how to obtain the thumbnail and file information based on the media file URI with temporary authorization. 176 177```ts 178import { picker } from '@kit.CoreFileKit'; 179import { photoAccessHelper } from '@kit.MediaLibraryKit'; 180import { BusinessError } from '@kit.BasicServicesKit'; 181import { dataSharePredicates } from '@kit.ArkData'; 182 183// Define an array of URIs to hold the URIs returned by PhotoViewPicker.select. 184let uris: Array<string> = []; 185const context = getContext(this); 186 187// Call PhotoViewPicker.select to select an image. 188async function photoPickerGetUri() { 189 try { 190 let PhotoSelectOptions = new picker.PhotoSelectOptions(); 191 PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; 192 PhotoSelectOptions.maxSelectNumber = 1; 193 let photoPicker = new picker.PhotoViewPicker(); 194 photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => { 195 console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); 196 uris = PhotoSelectResult.photoUris; 197 }).catch((err: BusinessError) => { 198 console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); 199 }); 200 } catch (error) { 201 let err: BusinessError = error as BusinessError; 202 console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); 203 } 204} 205 206async function uriGetAssets() { 207try { 208 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 209 let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 210 // Configure search criteria to query the image based on the URI returned by PhotoViewPicker.select. 211 predicates.equalTo('uri', uris[0]); 212 let fetchOption: photoAccessHelper.FetchOptions = { 213 fetchColumns: [photoAccessHelper.PhotoKeys.WIDTH, photoAccessHelper.PhotoKeys.HEIGHT, photoAccessHelper.PhotoKeys.TITLE, photoAccessHelper.PhotoKeys.DURATION], 214 predicates: predicates 215 }; 216 let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption); 217 // Obtain the PhotoAsset object corresponding to the URI. The file information is obtained from the PhotoAsset object. 218 const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); 219 console.info('asset displayName: ', asset.displayName); 220 console.info('asset uri: ', asset.uri); 221 console.info('asset photoType: ', asset.photoType); 222 console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH)); 223 console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT)); 224 console.info('asset title: ' + asset.get(photoAccessHelper.PhotoKeys.TITLE)); 225 // Obtain the thumbnail. 226 asset.getThumbnail((err, pixelMap) => { 227 if (err == undefined) { 228 console.info('getThumbnail successful ' + JSON.stringify(pixelMap)); 229 } else { 230 console.error('getThumbnail fail', err); 231 } 232 }); 233 } catch (error){ 234 console.error('uriGetAssets failed with err: ' + JSON.stringify(error)); 235 } 236} 237``` 238<!--Del--> 239## Copying A File by URI (for System Applications Only) 240 241To copy a file to the specified directory based on the URI, perform the following: 242 2431. Use [createFileAccessHelper](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#fileaccesscreatefileaccesshelper) to create a **fileAccessHelper** instance. 244 2452. Obtain **srcUri** of the file to copy. 246 2473. Obtain **destUri** of the file. 248 2494. Obtain the alternative file name **fileName**. 250 2515. Use helper.[copyFile](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#copyfile11)(srcUri, destUri, fileName) to copy the file to the specified directory. 252 253Sample code: 254 255``` 256import { BusinessError } from '@kit.BasicServicesKit'; 257import { Want } from '@kit.AbilityKit'; 258import { common } from '@kit.AbilityKit'; 259import { fileAccess } from '@kit.CoreFileKit'; 260 261// context is passed by EntryAbility. 262let context = getContext(this) as common.UIAbilityContext; 263async function example() { 264 let fileAccessHelper: fileAccess.FileAccessHelper; 265 // Obtain wantInfos by using getFileAccessAbilityInfo(). 266 let wantInfos: Array<Want> = [ 267 { 268 bundleName: "com.ohos.UserFile.ExternalFileManager", 269 abilityName: "FileExtensionAbility", 270 }, 271 ] 272 try { 273 fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos); 274 if (!fileAccessHelper) { 275 console.error("createFileAccessHelper interface returns an undefined object"); 276 } 277 // A built-in storage directory is used as an example. 278 // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. 279 // Use the URI obtained. 280 let sourceUri: string = "file://docs/storage/Users/currentUser/Download/one.txt"; 281 // URI of the directory to which the file is copied. 282 let destUri: string = "file://docs/storage/Users/currentUser/Documents"; 283 // File name to use if a file name conflict occurs. 284 let displayName: string = "file1.txt"; 285 // URI of the file to return. 286 let fileUri: string; 287 try { 288 // Copy a file and return the URI of the file generated. 289 fileUri = await fileAccessHelper.copyFile(sourceUri, destUri, displayName); 290 if (!fileUri) { 291 console.error("copyFile return undefined object"); 292 } 293 console.log("copyFile success, fileUri: " + JSON.stringify(fileUri)); 294 } catch (err) { 295 let error: BusinessError = err as BusinessError; 296 console.error("copyFile failed, errCode:" + error.code + ", errMessage:" + error.message); 297 } 298 } catch (err) { 299 let error: BusinessError = err as BusinessError; 300 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); 301 } 302 } 303``` 304<!--DelEnd--> 305