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