1# User File URI 2<!--Kit: Core File Kit--> 3<!--Subsystem: FileManagement--> 4<!--Owner: @wang_zhangjun; @zhuangzhuang--> 5<!--Designer: @wang_zhangjun; @zhuangzhuang; @renguang1116--> 6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang--> 7<!--Adviser: @foryourself--> 8 9As 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. 10 11## URI Types 12 13URIs can be classified into the following types: 14 15- 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). 16- 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). 17 18 19 20## Document URI 21 22### Overview 23 24The document URIs are in the following format: 25 26'file://docs/storage/Users/currentUser/\<relative_path\>/test.txt' 27 28The following table describes the fields in a document URI. 29 30| URI Field | Description | 31| ------------- | ------------------- | 32| 'file://docs/storage/Users/currentUser/' | Root directory of the file manager.| 33| '\<relative_path\>/' | Relative path of the file, for example, **Download/** and **Documents/**.| 34| 'test.txt' | 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.| 35 36### Obtaining a Document URI 37 381. Call **select()** or **save()** of [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) to select or save a document. 39 402. 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--> 41 423. 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 system applications. The file URIs of the following directories can be obtained: 43 - External storage directory 44 - **Docs** directory 45 - **Download** directory 46 - **Desktop** directory 47 - **Documents** directory 48 - **Share** directory of the shared disk 49<!--DelEnd--> 50 51### Using a Document URI 52 53Applications 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--> 54 55Applications 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 the **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. 56 571. Use [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) to create a document. The URI of the document is returned. 582. Rename the document based on its URI. 59 60```ts 61import { BusinessError } from '@kit.BasicServicesKit'; 62import { Want } from '@kit.AbilityKit'; 63import { common } from '@kit.AbilityKit'; 64import { fileAccess } from '@kit.CoreFileKit'; 65// The context is passed from EntryAbility. Ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 66let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 67 68async function example(context: common.UIAbilityContext) { 69 let fileAccessHelper: fileAccess.FileAccessHelper; 70 // Obtain wantInfos by using getFileAccessAbilityInfo(). 71 let wantInfos: Array<Want> = [ 72 { 73 bundleName: "com.ohos.UserFile.ExternalFileManager", 74 abilityName: "FileExtensionAbility", 75 }, 76 ] 77 try { 78 fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos); 79 if (!fileAccessHelper) { 80 console.error("createFileAccessHelper interface returns an undefined object"); 81 } 82 // A built-in storage directory is used as an example. 83 // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. 84 // Use the URI obtained. 85 let sourceUri: string = "file://docs/storage/Users/currentUser/Download"; 86 let displayName: string = "file1.txt"; 87 let fileUri: string; 88 try { 89 // Create a document. The URI of the document created is returned. 90 fileUri = await fileAccessHelper.createFile(sourceUri, displayName); 91 if (!fileUri) { 92 console.error("createFile return undefined object"); 93 } 94 console.info("createFile success, fileUri: " + JSON.stringify(fileUri)); 95 // Rename the document. The URI of the renamed document is returned. 96 let renameUri = await fileAccessHelper.rename(fileUri, "renameFile.txt"); 97 console.info("rename success, renameUri: " + JSON.stringify(renameUri)); 98 } catch (err) { 99 let error: BusinessError = err as BusinessError; 100 console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); 101 } 102 } catch (err) { 103 let error: BusinessError = err as BusinessError; 104 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); 105 } 106 } 107``` 108<!--DelEnd--> 109 110## Media File URI 111 112### Overview 113 114The URI format varies depending on the media file type. 115 116Image URI format: 117 118- 'file://media/Photo/\<id\>/IMG_datetime_0001/displayName.jpg' 119 120Video URI format: 121 122- 'file://media/Photo/\<id>/VID_datetime_0001/displayName.mp4' 123 124Audio URI format: 125 126- 'file://media/Audio/\<id>/AUD_datetime_0001/displayName.mp3' 127 128The following table describes the fields in a media file URI. 129 130| URI Field | Description | 131| ------------- | ------------------- | 132| 'file://media' | URI of a media file.| 133| 'Photo' | URI of an image or video.| 134| 'Audio' | URI of an audio file.| 135| '\<id>' | 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 files in the database.| 136| 'IMG_datetime_0001' | Name of the image stored in the user file system without the file name extension.| 137| 'VID_datetime_0001' | Name of the video stored in the user file system without the file name extension.| 138| 'AUD_datetime_0001' | Name of the audio file stored in the user file system without the file name extension.| 139|<!--DelRow--> 'displayName.jpg' | 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.| 140|<!--DelRow--> 'displayName.mp4' | 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.| 141|<!--DelRow--> 'displayName.mp3' | 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.| 142 143### Obtaining a Media File URI 144 1451. Call [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoViewPicker.md) to select media files. The URIs of the selected files are returned. 146 1472. Call [getAssets](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoAccessHelper.md#getassets) or [createAsset](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoAccessHelper.md#createasset) API in [photoAccessHelper](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper.md) to obtain the URIs of the selected files.<!--Del--> 148 1493. 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). 150<!--DelEnd--> 151 152### Using a Media File URI 153 154Applications of the normal APL can call [photoAccessHelper](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper.md) APIs to process media files based on their URIs. 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 API, the application must have the [ohos.permission.READ_IMAGEVIDEO](../media/medialibrary/photoAccessHelper-overview.md#available-capabilities) permission.<!--Del--> 155 156Applications of the system_basic or system_core level can call APIs of the **photoAccessHelper** and [userFileManager](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md) modules to use the media file URI. For more details, see the API reference of these modules. 157<!--DelEnd--> 158 159If you do not want to request the permission for a normal application, call [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoViewPicker.md) to obtain the file URI and call [photoAccessHelper.getAssets](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoAccessHelper.md#getassets) to obtain the **PhotoAsset** object based on the URI. Based on the **PhotoAsset** object, you can use [getThumbnail](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoAsset.md#getthumbnail) to obtain the image thumbnail or use [get](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-PhotoAsset.md#get) to obtain information from [PhotoKeys](../reference/apis-media-library-kit/arkts-apis-photoAccessHelper-e.md#photokeys). 160 161The following information can be obtained from **PhotoKeys** through temporary authorization: 162 163| Name | Value | Description | 164| ------------- | ------------------- | ---------------------------------------------------------- | 165| URI | 'uri' | URI of the file. | 166| PHOTO_TYPE | 'media_type' | Type of the media file. | 167| DISPLAY_NAME | 'display_name' | File name displayed. | 168| SIZE | 'size' | Size of the file. | 169| DATE_ADDED | 'date_added' | Unix timestamp when the file was added, in seconds. | 170| DATE_MODIFIED | 'date_modified' | Unix timestamp when the file content (not the file name) was last modified, in seconds. | 171| DURATION | 'duration' | Duration, in milliseconds. | 172| WIDTH | 'width' | Image width, in pixels. | 173| HEIGHT | 'height' | Image height, in pixels. | 174| DATE_TAKEN | 'date_taken' | Unix timestamp when the photo was taken, in seconds. | 175| ORIENTATION | 'orientation' | Orientation of the image file. | 176| TITLE | 'title' | Title in the file. | 177 178The following example shows how to obtain the thumbnail and file information based on the media file URI with temporary authorization. 179 180```ts 181import { photoAccessHelper } from '@kit.MediaLibraryKit'; 182import { BusinessError } from '@kit.BasicServicesKit'; 183import { dataSharePredicates } from '@kit.ArkData'; 184import { common } from '@kit.AbilityKit'; 185 186// Define a URI array to receive the URIs returned by PhotoViewPicker.select. 187let uris: Array<string> = []; 188// The context is passed from EntryAbility. Ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 189let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 190 191// Call PhotoViewPicker.select to select an image. 192async function photoPickerGetUri(context: common.UIAbilityContext) { 193 try { 194 let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); 195 PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; 196 PhotoSelectOptions.maxSelectNumber = 1; 197 let photoPicker = new photoAccessHelper.PhotoViewPicker(); 198 photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => { 199 console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult)); 200 uris = PhotoSelectResult.photoUris; 201 }).catch((err: BusinessError) => { 202 console.error(`PhotoViewPicker.select failed with err, code is ${err.code}, message is ${err.message}`); 203 }); 204 } catch (error) { 205 let err: BusinessError = error as BusinessError; 206 console.error(`PhotoViewPicker failed with err, code is ${err.code}, message is ${err.message}`); 207 } 208} 209 210async function uriGetAssets() { 211try { 212 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 213 let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 214 // Configure search criteria to query the image based on the URI returned by PhotoViewPicker.select. 215 predicates.equalTo('uri', uris[0]); 216 let fetchOption: photoAccessHelper.FetchOptions = { 217 fetchColumns: [photoAccessHelper.PhotoKeys.WIDTH, photoAccessHelper.PhotoKeys.HEIGHT, photoAccessHelper.PhotoKeys.TITLE, photoAccessHelper.PhotoKeys.DURATION], 218 predicates: predicates 219 }; 220 let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption); 221 // Obtain the PhotoAsset object corresponding to the URI. The file information is obtained from the PhotoAsset object. 222 const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject(); 223 console.info('asset displayName: ', asset.displayName); 224 console.info('asset uri: ', asset.uri); 225 console.info('asset photoType: ', asset.photoType); 226 console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH)); 227 console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT)); 228 console.info('asset title: ' + asset.get(photoAccessHelper.PhotoKeys.TITLE)); 229 // Obtain the thumbnail. 230 asset.getThumbnail((err, pixelMap) => { 231 if (err == undefined) { 232 console.info('getThumbnail successful ' + JSON.stringify(pixelMap)); 233 } else { 234 console.error('getThumbnail fail', err); 235 } 236 }); 237 } catch (error){ 238 console.error(`uriGetAssets failed with err, code is ${error.code}, message is ${error.message}`); 239 } 240} 241``` 242<!--Del--> 243## Copying a File by URI (for System Applications Only) 244 245To copy a file to the specified directory based on the URI, perform the following: 246 2471. Call [createFileAccessHelper](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#fileaccesscreatefileaccesshelper) to create a **fileAccessHelper** instance. 248 2492. Obtain **srcUri** of the file to copy. 250 2513. Obtain **destUri** of the file. 252 2534. Obtain the alternative file name **fileName**. 254 2555. 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. 256 257Sample code: 258 259```ts 260import { BusinessError } from '@kit.BasicServicesKit'; 261import { Want } from '@kit.AbilityKit'; 262import { common } from '@kit.AbilityKit'; 263import { fileAccess } from '@kit.CoreFileKit'; 264 265// The context is passed from EntryAbility. Ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 266let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 267async function example(context: common.UIAbilityContext) { 268 let fileAccessHelper: fileAccess.FileAccessHelper; 269 // Obtain wantInfos by using getFileAccessAbilityInfo(). 270 let wantInfos: Array<Want> = [ 271 { 272 bundleName: "com.ohos.UserFile.ExternalFileManager", 273 abilityName: "FileExtensionAbility", 274 }, 275 ] 276 try { 277 fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos); 278 if (!fileAccessHelper) { 279 console.error("createFileAccessHelper interface returns an undefined object"); 280 } 281 // A built-in storage directory is used as an example. 282 // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. 283 // Use the URI obtained. 284 let sourceUri: string = "file://docs/storage/Users/currentUser/Download/one.txt"; 285 // URI of the directory to which the file is copied. 286 let destUri: string = "file://docs/storage/Users/currentUser/Documents"; 287 // File name to use if a file name conflict occurs. 288 let displayName: string = "file1.txt"; 289 // URI of the file to return. 290 let fileUri: string; 291 try { 292 // Copy a file and return the URI of the file generated. 293 fileUri = await fileAccessHelper.copyFile(sourceUri, destUri, displayName); 294 if (!fileUri) { 295 console.error("copyFile return undefined object"); 296 } 297 console.info("copyFile success, fileUri: " + JSON.stringify(fileUri)); 298 } catch (err) { 299 let error: BusinessError = err as BusinessError; 300 console.error("copyFile failed, errCode:" + error.code + ", errMessage:" + error.message); 301 } 302 } catch (err) { 303 let error: BusinessError = err as BusinessError; 304 console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); 305 } 306 } 307``` 308<!--DelEnd--> 309