User File URI

As 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.

URI Types

The URIs in the system can be classified into the following types:

  • 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.
  • 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.

user-file-uri-intro

Document URI

Document URI Overview

The document URIs are in the following format:

'file://docs/storage/Users/currentUser/<relative_path>/test.txt'

The following table describes the fields in a document URI.

URI Field Description
'file://docs/storage/Users/currentUser/' Indicates the root directory of the file manager.
'<relative_path>/' Indicates the relative path of the file, for example, Download/ and Documents/.
'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.

Obtaining a Document URI

You can obtain the document URIs of the files and folders in the following directories:

  • External storage directory
  • Docs directory
  • Download directory
  • Desktop directory
  • Documents directory
  • Share directory of the shared disk

Using a Document URI

Applications of the normal APL can call @ohos.file.fs 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 and Saving Documents.

Applications of the system_basic or system_core APL can call @ohos.file.fs and @ohos.file.fileAccess 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.

  1. Use @ohos.file.fileAccess to create a document. The document URI is returned.
  2. Rename the document based on its URI.
import { BusinessError } from '@ohos.base';
import Want from '@ohos.app.ability.Want';
import common from '@ohos.app.ability.common';
import fileAccess from '@ohos.file.fileAccess';
// context is passed by EntryAbility.
let context = getContext(this) as common.UIAbilityContext;

async function example() {
    let fileAccessHelper: fileAccess.FileAccessHelper;
    // Obtain wantInfos by using getFileAccessAbilityInfo().
    let wantInfos: Array<Want> = [
      {
        bundleName: "com.ohos.UserFile.ExternalFileManager",
        abilityName: "FileExtensionAbility",
      },
    ]
    try {
      fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos);
      if (!fileAccessHelper) {
        console.error("createFileAccessHelper interface returns an undefined object");
      }
      // A built-in storage directory is used as an example.
      // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
      // Use the URI obtained.
      let sourceUri: string = "file://docs/storage/Users/currentUser/Download";
      let displayName: string = "file1.txt";
      let fileUri: string;
      try {
        // Create a document. The URI of the document created is returned.
        fileUri = await fileAccessHelper.createFile(sourceUri, displayName);
        if (!fileUri) {
          console.error("createFile return undefined object");
        }
        console.log("createFile success, fileUri: " + JSON.stringify(fileUri));
        // Rename the document. The URI of the renamed document is returned.
        let renameUri = await fileAccessHelper.rename(fileUri, "renameFile.txt");
        console.log("rename success, renameUri: " + JSON.stringify(renameUri));
      } catch (err) {
        let error: BusinessError = err as BusinessError;
        console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message);
      }
    } catch (err) {
      let error: BusinessError = err as BusinessError;
      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
    }
  }

Media File URI

Media File URI Overview

The URI format varies depending on the media file type.

  • Image URI format:

    'file://media/Photo/<id>/IMG_datetime_0001/displayName.jpg'

  • Video URI format:

    'file://media/Photo/<id>/VID_datetime_0001/displayName.mp4'

  • Audio file URI format:

    'file://media/Audio/<id>/AUD_datetime_0001/displayName.mp3'

The following table describes the fields in a media file URI.

URI Field Description
'file://media' Indicates a URI of a media file.
'Photo' Indicates a URI of an image or video.
'Audio' Indicates a URI of an audio file.
'<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.
'IMG_datetime_0001' Indicates the name of the image stored in the user file system without the file name extension.
'VID_datetime_0001' Indicates the name of the video stored in the user file system without the file name extension.
'AUD_datetime_0001' Indicates the name of the audio file stored in the user file system without the file name extension.
'displayName.jpg' Indicates the image name displayed. You can use userFileManager.commitModify to rename it. Note that the URI of the new image name is also changed.
'displayName.mp4' Indicates the video name displayed. You can use userFileManager.commitModify to rename it. Note that the URI of the new video name is also changed.
'displayName.mp3' Indicates the audio file name displayed. You can use userFileManager.commitModify to rename it. Note that the URI of the new audio file name is also changed.

Obtaining a Media File URI

Using a Media File URI

Applications of the normal APL can call photoAccessHelper APIs to process media files based on their URI. For details about the sample code, see Obtaining an Image or Video by URI. To call the APIs, the application must have the ohos.permission.READ_IMAGEVIDEO permission.

Applications of the system_basic or system_core APL can call photoAccessHelper and userFileManager APIs to process media files based on their URI. For details about how to use the APIs, see the API reference document.

Without the ohos.permission.READ_IMAGEVIDEO permission, the application of the normal APL can use PhotoViewPicker.select to obtain the URI, and use photoAccessHelper.getAssets to obtain the PhotoAsset object corresponding to the URI. The PhotoAsset object can be used to call getThumbnail to obtain the thumbnail and call get to read certain information in PhotoKeys.

The following information can be obtained from PhotoKeys through temporary authorization:

Name Value Description
URI 'uri' URI of the file.
PHOTO_TYPE 'media_type' Type of the media file.
DISPLAY_NAME 'display_name' File name displayed.
SIZE 'size' Size of the file.
DATE_ADDED 'date_added' Date when the file was added. The value is the number of seconds elapsed since the Epoch time.
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.
DURATION 'duration' Duration, in ms.
WIDTH 'width' Image width, in pixels.
HEIGHT 'height' Image height, in pixels.
DATE_TAKEN 'date_taken' Date when the photo was taken. The value is the number of seconds elapsed since the Epoch time.
ORIENTATION 'orientation' Orientation of the image file.
TITLE 'title' Title in the file.

The following example shows how to obtain the thumbnail and file information based on the media file URI with temporary authorization.

import picker from '@ohos.file.picker';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { BusinessError } from '@ohos.base';
import dataSharePredicates from '@ohos.data.dataSharePredicates';

// Define an array of URIs to hold the URIs returned by PhotoViewPicker.select.
let uris: Array<string> = [];
const context = getContext(this);

// Call PhotoViewPicker.select to select an image.
async function photoPickerGetUri() {
  try {  
    let PhotoSelectOptions = new picker.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new picker.PhotoViewPicker();
    photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => {
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
      uris = PhotoSelectResult.photoUris;
    }).catch((err: BusinessError) => {
      console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}

async function uriGetAssets() {
try {
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    // Configure search criteria to query the image based on the URI returned by PhotoViewPicker.select.
    predicates.equalTo('uri', uris[0]);
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    // Obtain the PhotoAsset object corresponding to the URI. The file information is obtained from the PhotoAsset object.
    const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    console.info('asset displayName: ', asset.displayName);
    console.info('asset uri: ', asset.uri);
    console.info('asset photoType: ', asset.photoType);
    console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH));
    console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT));
    console.info('asset title: ' + asset.get(photoAccessHelper.PhotoKeys.TITLE));
    // Obtain the thumbnail.
    asset.getThumbnail((err, pixelMap) => {
      if (err == undefined) {
        console.info('getThumbnail successful ' + JSON.stringify(pixelMap));
      } else {
        console.error('getThumbnail fail', err);
      }
    });
  } catch (error){
    console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
  }
}

Copying A File by URI

To copy a file to the specified directory based on the URI, perform the following:

  1. Use createFileAccessHelper to create a fileAccessHelper instance.

  2. Obtain srcUri of the file to copy.

  3. Obtain destUri of the file.

  4. Obtain the alternative file name fileName.

  5. Use helper.copyFile(srcUri, destUri, fileName) to copy the file to the specified directory.

Sample code:

import { BusinessError } from '@ohos.base';
import Want from '@ohos.app.ability.Want';
import common from '@ohos.app.ability.common';
import fileAccess from '@ohos.file.fileAccess';

async example() {
    let fileAccessHelper: fileAccess.FileAccessHelper;
    // Obtain wantInfos by using getFileAccessAbilityInfo().
    let wantInfos: Array<Want> = [
      {
        bundleName: "com.ohos.UserFile.ExternalFileManager",
        abilityName: "FileExtensionAbility",
      },
    ]
    try {
      // context is passed by EntryAbility.
      let context = getContext(this) as common.UIAbilityContext;
      fileAccessHelper = fileAccess.createFileAccessHelper(context, wantInfos);
      if (!fileAccessHelper) {
        console.error("createFileAccessHelper interface returns an undefined object");
      }
      // A built-in storage directory is used as an example.
      // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo.
      // Use the URI obtained.
      let sourceUri: string = "file://docs/storage/Users/currentUser/Download/one.txt";
      // URI of the directory to which the file is copied.
      let destUri: string = "file://docs/storage/Users/currentUser/Documents";
      // File name to use if a file name conflict occurs.
      let displayName: string = "file1.txt";
      // URI of the file to return. 
      let fileUri: string;
      try {
        // Copy a file and return the URI of the file generated.
        fileUri = await fileAccessHelper.copyFile(sourceUri, destUri, displayName);
        if (!fileUri) {
          console.error("copyFile return undefined object");
        }
        console.log("copyFile success, fileUri: " + JSON.stringify(fileUri));
      } catch (err) {
        let error: BusinessError = err as BusinessError;
        console.error("copyFile failed, errCode:" + error.code + ", errMessage:" + error.message);
      }
    } catch (err) {
      let error: BusinessError = err as BusinessError;
      console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message);
    }
  }