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 stored in the user file system. The supported file types vary, depending on the file manager used. Common file types include TXT, JPG, MP4, and MP3. | 29 30### Obtaining a Document URI 31 32- Call **select()** or **save()** of [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) to select or save a document. 33- Call **select()** or **save()** of [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) to select or save an audio file.<!--Del--> 34- Call [@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 system applications. 35 36You can obtain the document URIs of the files and folders in the following directories: 37 38- External storage directory 39- **Docs** directory 40- **Download** directory 41- **Desktop** directory 42- **Documents** directory 43- **Share** directory of the shared disk 44<!--DelEnd--> 45 46### Using a Document URI 47 48Applications 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--> 49 50Applications 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. 51 521. Call [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) to create a document. The URI of the document is returned. 532. Rename the document based on its URI. 54 55```ts 56import { BusinessError } from '@kit.BasicServicesKit'; 57import { Want } from '@kit.AbilityKit'; 58import { common } from '@kit.AbilityKit'; 59import { fileAccess } from '@kit.CoreFileKit'; 60// context is passed by EntryAbility. 61let context = getContext(this) as common.UIAbilityContext; 62 63async function example() { 64 let fileAccessHelper: fileAccess.FileAccessHelper; 65 // Obtain wantInfos by using getFileAccessAbilityInfo(). 66 let wantInfos: Array<Want> = [ 67 { 68 bundleName: "com.ohos.UserFile.ExternalFileManager", 69 abilityName: "FileExtensionAbility", 70 }, 71 ] 72 try { 73 fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos); 74 if (!fileAccessHelper) { 75 console.error("createFileAccessHelper interface returns an undefined object"); 76 } 77 // A built-in storage directory is used as an example. 78 // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. 79 // Use the URI obtained. 80 let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; 81 let displayName: string = "file1.txt"; 82 let fileUri: string; 83 try { 84 // Create a document. The URI of the document created is returned. 85 fileUri = await fileAccessHelper.createFile(sourceUri, displayName); 86 if (!fileUri) { 87 console.error("createFile return undefined object"); 88 } 89 console.log("createFile success, fileUri: " + JSON.stringify(fileUri)); 90 // Rename the document. The URI of the renamed document is returned. 91 let renameUri = await fileAccessHelper.rename(fileUri, "renameFile.txt"); 92 console.log("rename success, renameUri: " + JSON.stringify(renameUri)); 93 } catch (err) { 94 let error: BusinessError = err as BusinessError; 95 console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); 96 } 97 } catch (err) { 98 let error: BusinessError = err as BusinessError; 99 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); 100 } 101 } 102``` 103<!--DelEnd--> 104 105## Media File URI 106 107### Media File URI Overview 108 109The URI format varies depending on the media file type. 110 111- Image URI format: 112 113 'file://media/Photo/\<id\>/IMG_datetime_0001/displayName.jpg' 114 115- Video URI format: 116 117 'file://media/Photo/\<id>/VID_datetime_0001/displayName.mp4' 118 119- Audio file URI format: 120 121 'file://media/Audio/\<id>/AUD_datetime_0001/displayName.mp3' 122 123The following table describes the fields in a media file URI. 124 125| URI Field | Description | 126| ------------- | ------------------- | 127| 'file://media' | Indicates a URI of a media file.| 128| 'Photo' | Indicates a URI of an image or video.| 129| 'Audio' | Indicates a URI of an audio file.| 130| '\<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.| 131| 'IMG_datetime_0001' | Indicates the name of the image stored in the user file system without the file name extension.| 132| 'VID_datetime_0001' | Indicates the name of the video stored in the user file system without the file name extension.| 133| 'AUD_datetime_0001' | Indicates the name of the audio file stored in the user file system without the file name extension.| 134|<!--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.| 135|<!--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.| 136|<!--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.| 137 138### Obtaining a Media File URI 139 140- Call [PhotoAccessHelper.PhotoViewPicker](../media/medialibrary/photoAccessHelper-photoviewpicker.md) to select media files. The URIs of the selected files are returned. 141 142- Call [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--> 143 144- Call [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). 145 <!--DelEnd--> 146 147### Using a Media File URI 148 149Applications 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--> 150 151Applications 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. 152<!--DelEnd--> 153 154If you do not want to request the permission for a normal application, call [PhotoAccessHelper.PhotoViewPicker](../media/medialibrary/photoAccessHelper-photoviewpicker.md) to obtain the file URI and call [photoAccessHelper.getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) to obtain the **PhotoAsset** object based on 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). 155 156The following information can be obtained from **PhotoKeys** through temporary authorization: 157 158| Name | Value | Description | 159| ------------- | ------------------- | ---------------------------------------------------------- | 160| URI | 'uri' | URI of the file. | 161| PHOTO_TYPE | 'media_type' | Type of the media file. | 162| DISPLAY_NAME | 'display_name' | File name displayed. | 163| SIZE | 'size' | Size of the file. | 164| DATE_ADDED | 'date_added' | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | 165| 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.| 166| DURATION | 'duration' | Duration, in ms. | 167| WIDTH | 'width' | Image width, in pixels. | 168| HEIGHT | 'height' | Image height, in pixels. | 169| DATE_TAKEN | 'date_taken' | Date when the photo was taken. The value is the number of seconds elapsed since the Epoch time. | 170| ORIENTATION | 'orientation' | Orientation of the image file. | 171| TITLE | 'title' | Title in the file. | 172 173The following example shows how to obtain the thumbnail and file information based on the media file URI with temporary authorization. 174 175```ts 176import { photoAccessHelper } from '@kit.MediaLibraryKit'; 177import { BusinessError } from '@kit.BasicServicesKit'; 178import { dataSharePredicates } from '@kit.ArkData'; 179 180// Define an array of URIs to hold the URIs returned by PhotoViewPicker.select. 181let uris: Array<string> = []; 182const context = getContext(this); 183 184// Call PhotoViewPicker.select to select an image. 185async function photoPickerGetUri() { 186 try { 187 let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); 188 PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; 189 PhotoSelectOptions.maxSelectNumber = 1; 190 let photoPicker = new photoAccessHelper.PhotoViewPicker(); 191 photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => { 192 console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); 193 uris = PhotoSelectResult.photoUris; 194 }).catch((err: BusinessError) => { 195 console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err)); 196 }); 197 } catch (error) { 198 let err: BusinessError = error as BusinessError; 199 console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err)); 200 } 201} 202 203async function uriGetAssets() { 204try { 205 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 206 let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 207 // Configure search criteria to query the image based on the URI returned by PhotoViewPicker.select. 208 predicates.equalTo('uri', uris[0]); 209 let fetchOption: photoAccessHelper.FetchOptions = { 210 fetchColumns: [photoAccessHelper.PhotoKeys.WIDTH, photoAccessHelper.PhotoKeys.HEIGHT, photoAccessHelper.PhotoKeys.TITLE, photoAccessHelper.PhotoKeys.DURATION], 211 predicates: predicates 212 }; 213 let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption); 214 // Obtain the PhotoAsset object corresponding to the URI. The file information is obtained from the PhotoAsset object. 215 const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); 216 console.info('asset displayName: ', asset.displayName); 217 console.info('asset uri: ', asset.uri); 218 console.info('asset photoType: ', asset.photoType); 219 console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH)); 220 console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT)); 221 console.info('asset title: ' + asset.get(photoAccessHelper.PhotoKeys.TITLE)); 222 // Obtain the thumbnail. 223 asset.getThumbnail((err, pixelMap) => { 224 if (err == undefined) { 225 console.info('getThumbnail successful ' + JSON.stringify(pixelMap)); 226 } else { 227 console.error('getThumbnail fail', err); 228 } 229 }); 230 } catch (error){ 231 console.error('uriGetAssets failed with err: ' + JSON.stringify(error)); 232 } 233} 234``` 235<!--Del--> 236## Copying A File by URI (for System Applications Only) 237 238To copy a file to the specified directory based on the URI, perform the following: 239 2401. Call [createFileAccessHelper](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#fileaccesscreatefileaccesshelper) to create a **fileAccessHelper** instance. 241 2422. Obtain **srcUri** of the file to copy. 243 2443. Obtain **destUri** of the file. 245 2464. Obtain the alternative file name **fileName**. 247 2485. Call helper.[copyFile](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#copyfile11)(srcUri, destUri, fileName) to copy the file to the specified directory. 249 250Sample code: 251 252``` 253import { BusinessError } from '@kit.BasicServicesKit'; 254import { Want } from '@kit.AbilityKit'; 255import { common } from '@kit.AbilityKit'; 256import { fileAccess } from '@kit.CoreFileKit'; 257 258// context is passed by EntryAbility. 259let context = getContext(this) as common.UIAbilityContext; 260async function example() { 261 let fileAccessHelper: fileAccess.FileAccessHelper; 262 // Obtain wantInfos by using getFileAccessAbilityInfo(). 263 let wantInfos: Array<Want> = [ 264 { 265 bundleName: "com.ohos.UserFile.ExternalFileManager", 266 abilityName: "FileExtensionAbility", 267 }, 268 ] 269 try { 270 fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos); 271 if (!fileAccessHelper) { 272 console.error("createFileAccessHelper interface returns an undefined object"); 273 } 274 // A built-in storage directory is used as an example. 275 // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. 276 // Use the URI obtained. 277 let sourceUri: string = "file://docs/storage/Users/currentUser/Download/one.txt"; 278 // URI of the directory to which the file is copied. 279 let destUri: string = "file://docs/storage/Users/currentUser/Documents"; 280 // File name to use if a file name conflict occurs. 281 let displayName: string = "file1.txt"; 282 // URI of the file to return. 283 let fileUri: string; 284 try { 285 // Copy a file and return the URI of the file generated. 286 fileUri = await fileAccessHelper.copyFile(sourceUri, destUri, displayName); 287 if (!fileUri) { 288 console.error("copyFile return undefined object"); 289 } 290 console.log("copyFile success, fileUri: " + JSON.stringify(fileUri)); 291 } catch (err) { 292 let error: BusinessError = err as BusinessError; 293 console.error("copyFile failed, errCode:" + error.code + ", errMessage:" + error.message); 294 } 295 } catch (err) { 296 let error: BusinessError = err as BusinessError; 297 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); 298 } 299 } 300``` 301<!--DelEnd--> 302