Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

FileUtils

The FileUtils singleton provides file operations like reading, writing and listing files. More...

Import Statement: import Felgo 4.0
Since: Felgo 2.17.0

Properties

Methods

Detailed Description

This item is available as a singleton item from all QML components when Felgo is imported via import Felgo. It is accessible with the name FileUtils. It encapsulates methods that allow to read, write and list files.

Note: This type is now available as a QML singleton type as of Felgo 4.0.0. Use it with the upper-case name instead of the lower-case context property name.

This is an example to download a PDF file and then open it with the native PDF viewer application, using FileUtils::openFile(). It also uses the DownloadableResource type to download a pdf from a web location and store it on the device.

 import Felgo
 import QtQuick

 App {
   id: app
   // uncomment this to remove the resources on startup, so you can test the downloading again
   //Component.onCompleted: pdfResource.remove()
   NavigationStack {
     AppPage {
       title: "Download PDF"

       Column {
         anchors.centerIn: parent

         AppButton {
           text: "Download / Open"
           onClicked: {
             if(pdfResource.available) openPdf()
             else pdfResource.download()
           }
         }
         AppText {
           text: "Status: " + pdfResource.status
         }
       }
     }
   }
   DownloadableResource {
     id: pdfResource
     source: "http://www.orimi.com/pdf-test.pdf"
     storageLocation: FileUtils.DocumentsLocation
     storageName: "pdf-test.pdf"
     extractAsPackage: false
     // if the download is competed, available will be set to true
     onAvailableChanged: if(available) openPdf()
   }
   function openPdf() {
     // you can also open files with NativeUtils.openUrl() now (for paths starting with "file://")
     //NativeUtils.openUrl(pdfResource.storagePath)
     FileUtils.openFile(pdfResource.storagePath)
   }
 }

Requirements for Reading Files on Android

To be able to read files with another app on Android, please make sure that the following 2 conditions are met:

  • You need to enable the paths you wish to use in android/res/xml/file_paths.xml. If this file does not exist yet, please create it. The default content is:
     <?xml version="1.0" encoding="utf-8"?>
     <paths>
     <files-path name="files" path="."/>
     <cache-path name="cache" path="."/>
     <external-path name="external" path="."/>
     </paths>
  • You need to specify a file provider in android/AndroidManifest.xml. You can add the following code just before the closing </application> tag (so it is a child of the <application>):
     <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
       <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/>
     </provider>

Storage Location

The StorageLocation enumeration in FileUtils encapsulates the QStandardPaths for access in QML.

You can use these values with storageLocation() to obtain a writable path. DownloadableResource downloads and extracts files to these locations using its storageLocation property.

The following location types are supported:

Location Description
FileUtils.DesktopLocation Returns the user's desktop directory. This is a generic value on systems with no concept of a desktop.
FileUtils.DocumentsLocation Returns the directory containing user document files. This is a generic value. The returned path is never empty.
FileUtils.FontsLocation Returns the directory containing user's fonts. This is a generic value. Note that installing fonts may require additional, platform-specific operations.
FileUtils.ApplicationsLocation Returns the directory containing the user applications (either executables, application bundles, or shortcuts to them). This is a generic value. Note that installing applications may require additional, platform-specific operations. Files, folders or shortcuts in this directory are platform-specific.
FileUtils.MusicLocation Returns the directory containing the user's music or other audio files. This is a generic value. If no directory specific for music files exists, a sensible fallback for storing user documents is returned.
FileUtils.MoviesLocation Returns the directory containing the user's movies and videos. This is a generic value. If no directory specific for movie files exists, a sensible fallback for storing user documents is returned.
FileUtils.PicturesLocation Returns the directory containing the user's pictures or photos. This is a generic value. If no directory specific for picture files exists, a sensible fallback for storing user documents is returned.
FileUtils.TempLocation Returns a directory where temporary files can be stored. The returned value might be application-specific, shared among other applications for this user, or even system-wide. The returned path is never empty.
FileUtils.HomeLocation Returns the user's home directory (the same as QDir::homePath()). On Unix systems, this is equal to the HOME environment variable. This value might be generic or application-specific, but the returned path is never empty.
FileUtils.DataLocation Returns the same value as AppLocalDataLocation. This enumeration value is deprecated. Using AppDataLocation is preferable since on Windows, the roaming path is recommended.
FileUtils.CacheLocation Returns a directory location where user-specific non-essential (cached) data should be written. This is an application-specific directory. The returned path is never empty.
FileUtils.GenericDataLocation Returns a directory location where user-specific non-essential (cached) data, shared across applications, should be written. This is a generic value. Note that the returned path may be empty if the system has no concept of shared cache.
FileUtils.RuntimeLocation Returns a directory location where persistent data shared across applications can be stored. This is a generic value. The returned path is never empty.
FileUtils.ConfigLocation Returns a directory location where runtime communication files should be written, like Unix local sockets. This is a generic value. The returned path may be empty on some systems.
FileUtils.GenericConfigLocation Returns a directory location where user-specific configuration files should be written. This may be either a generic value or application-specific, and the returned path is never empty.
FileUtils.DownloadLocation Returns a directory for user's downloaded files. This is a generic value. If no directory specific for downloads exists, a sensible fallback for storing user documents is returned.
FileUtils.GenericCacheLocation Returns a directory location where user-specific configuration files shared between multiple applications should be written. This is a generic value and the returned path is never empty.
FileUtils.AppDataLocation Returns a directory location where persistent application data can be stored. This is an application-specific directory. To obtain a path to store data to be shared with other applications, use FileUtils.GenericDataLocation. The returned path is never empty. On the Windows operating system, this returns the roaming path.
FileUtils.AppLocalDataLocation Returns the local settings path on the Windows operating system. On all other platforms, it returns the same value as AppDataLocation.
FileUtils.AppConfigLocation Returns a directory location where user-specific configuration files should be written. This is an application-specific directory, and the returned path is never empty.

The resulting location depends on the underlying platform. Some might not be available on each platform. The function storageLocation() will then return an empty path.

Here are examples of the storage locations on each platform:

Location macOS Windows
FileUtils.DesktopLocation "~/Desktop" "C:/Users/<USER>/Desktop"
FileUtils.DocumentsLocation "~/Documents" "C:/Users/<USER>/Documents"
FileUtils.FontsLocation "/System/Library/Fonts" (not writable) "C:/Windows/Fonts" (not writable)
FileUtils.ApplicationsLocation "/Applications" (not writable) "C:/Users/<USER>/AppData/Roaming/Microsoft
/Windows/Start Menu/Programs"
FileUtils.MusicLocation "~/Music" "C:/Users/<USER>/Music"
FileUtils.MoviesLocation "~/Movies" "C:/Users/<USER>/Videos"
FileUtils.PicturesLocation "~/Pictures" "C:/Users/<USER>/Pictures"
FileUtils.TempLocation randomly generated by the OS "C:/Users/<USER>/AppData/Local/Temp"
FileUtils.HomeLocation "~" "C:/Users/<USER>"
FileUtils.DataLocation "~/Library/Application Support/<APPNAME>" "C:/ProgramData/<APPNAME>"
FileUtils.CacheLocation "~/Library/Caches/<APPNAME>" "C:/Users/<USER>/AppData/Local/<APPNAME>/cache"
FileUtils.GenericDataLocation "~/Library/Application Support" "C:/Users/<USER>/AppData/Local"
FileUtils.RuntimeLocation "~/Library/Application Support" "C:/Users/<USER>"
FileUtils.ConfigLocation "~/Library/Preferences" "C:/ProgramData/<APPNAME>"
FileUtils.GenericConfigLocation "~/Library/Preferences" "C:/Users/<USER>/AppData/Local"
FileUtils.DownloadLocation "~/Downloads" "C:/Users/<USER>/Downloads"
FileUtils.GenericCacheLocation "~/Library/Caches" "C:/Users/<USER>/AppData/Local/cache"
FileUtils.AppDataLocation "~/Library/Application Support/<APPNAME>" "C:/Users/<USER>/AppData/Roaming/<APPNAME>"
FileUtils.AppLocalDataLocation "~/Library/Application Support/<APPNAME>" "C:/Users/<USER>/AppData/Local/<APPNAME>"
FileUtils.AppConfigLocation "~/Library/Preferences/<APPNAME>" "C:/Users/<USER>/AppData/Local/<APPNAME>"
Location Linux
FileUtils.DesktopLocation "~/Desktop"
FileUtils.DocumentsLocation "~/Documents"
FileUtils.FontsLocation "~/.fonts"
FileUtils.ApplicationsLocation "~/.local/share/applications"
FileUtils.MusicLocation "~/Music"
FileUtils.MoviesLocation "~/Videos"
FileUtils.PicturesLocation "~/Pictures"
FileUtils.TempLocation "/tmp"
FileUtils.HomeLocation "~"
FileUtils.DataLocation "~/.local/share/<APPNAME>"
FileUtils.CacheLocation "~/.cache/<APPNAME>"
FileUtils.GenericDataLocation "~/.local/share"
FileUtils.RuntimeLocation "/run/user/<USER>"
FileUtils.ConfigLocation "~/.config"
FileUtils.GenericConfigLocation "~/.config"
FileUtils.DownloadLocation "~/Downloads"
FileUtils.GenericCacheLocation "~/.cache"
FileUtils.AppDataLocation "~/.local/share/<APPNAME>"
FileUtils.AppLocalDataLocation "~/.local/share/<APPNAME>"
FileUtils.AppConfigLocation "~/.config/<APPNAME>"
Location Android iOS
FileUtils.DesktopLocation "<APPROOT>/files" "<APPROOT>/Documents/Desktop"
FileUtils.DocumentsLocation "<USER>/Documents" "<APPROOT>/Documents"
FileUtils.FontsLocation "/system/fonts" (not writable) "<APPROOT>/Library/Fonts"
FileUtils.ApplicationsLocation not supported (directory not readable) not supported
FileUtils.ApplicationsLocation "<USER>/Music" "<APPROOT>/Documents/Music"
FileUtils.MoviesLocation "<USER>/Movies" "<APPROOT>/Documents/Movies"
FileUtils.PicturesLocation "<USER>/Pictures" "<APPROOT>/Documents/Pictures"
FileUtils.TempLocation "<APPROOT>/cache" "<APPROOT>/tmp"
FileUtils.HomeLocation "<APPROOT>/files" "<APPROOT>" (not writable)
FileUtils.DataLocation "<APPROOT>/files" "<APPROOT>/Library/Application Support"
FileUtils.CacheLocation "<APPROOT>/cache" "<APPROOT>/Library/Caches"
FileUtils.GenericDataLocation "<USER>" "<APPROOT>/Documents"
FileUtils.RuntimeLocation "<APPROOT>/cache" not supported
FileUtils.ConfigLocation "<APPROOT>/files/settings" "<APPROOT>/Library/Preferences"
FileUtils.GenericConfigLocation "<APPROOT>/files/settings" (there is no shared settings) "<APPROOT>/Library/Preferences"
FileUtils.DownloadLocation "<USER>/Downloads" "<APPROOT>/Documents/Downloads"
FileUtils.GenericCacheLocation "<APPROOT>/cache" (there is no shared cache) "<APPROOT>/Library/Caches"
FileUtils.AppDataLocation "<APPROOT>/files" "<APPROOT>/Library/Application Support"
FileUtils.AppLocalDataLocation "<APPROOT>/files/settings" "<APPROOT>/Library/Preferences/<APPNAME>"
FileUtils.AppConfigLocation "<APPROOT>/files" "<APPROOT>/Library/Application Support"

Multi-path URLs

FileUtils offers a function to find a file in multiple search locations. Use getMultiPathUrl() to retrieve a URL to a relative file path.

By default, this looks for files in the default location, which is the user's documents directory. Additional search paths can be added with addSearchPath. DownloadableResource automatically adds its storageLocation as search path, so files downloaded and extracted with it can be used right away with getMultiPathUrl().

Write, List, Read Files

The following example shows how to use writeFile() to write files to different folders. Afterwards the content is read and displayed with a Text element. Additionally, it lists the files of the Documents directory.

A JavaScript object is written to the file with JSON.stringify(). Afterwards it can be retrieved as object with JSON.parse().

  • A JavaScript object is converted to a JSON string with JSON.stringify().
  • A folder called Particles is created in the Documents directory.
  • A file called newParticle.json is created in this new folder. The JSON string is written to it.
  • A file called newConfig.json is created in the Documents directory. The JSON string is written to it.
  • Afterwards all .json files in the Documents directory and its subfolders are listed.
  • The newParticle.json file is read from the Particles folder in the Documents directory.
  • The original JavaScript object is parsed using JSON.parse().
 import Felgo
 import QtQuick

 GameWindow {

   Scene {
     id: scene

     Text {
       id: status
       anchors.fill: parent
       wrapMode: Text.WrapAtWordBoundaryOrAnywhere
       verticalAlignment: Text.AlignVCenter
       text: "Status:\n"
       color: "White"
     }

     Component.onCompleted: {
       var fileContentAsString = JSON.stringify({
                                                  data : "sampleData",
                                                  number: 7,
                                                  subArray: [1, 2, 3, 4],
                                                  subObject: { subData: "Hello world" }
                                                }, null, "  ")

       // write <Documents>/Particles/newParticle.json
       var fileName = FileUtils.storageLocation(FileUtils.DocumentsLocation, "Particles/newParticle.json")
       var success = FileUtils.writeFile(fileName, fileContentAsString)
       status.text += "Write Particles/newParticle.json success: " + success + "\n"

       if(!success)
         return

       // write <Documents>/newConfig.json
       fileName = FileUtils.storageLocation(FileUtils.DocumentsLocation, "newConfig.json")
       success = FileUtils.writeFile(fileName, fileContentAsString)
       status.text += "Write newConfig.json success: " + success + "\n"
       if(!success)
         return

       // list all .json files in <Documents>
       var dirName = FileUtils.storageLocation(FileUtils.DocumentsLocation)
       var stringList = FileUtils.listFiles(dirName, "*.json")

       var contentText = "\nFiles: \n"
       for(var i = 0; i < stringList.length; i++){
         contentText += stringList[i] + "\n"
       }

       // read <Documents>/Particles/newParticle.json
       fileName = FileUtils.storageLocation(FileUtils.DocumentsLocation, "Particles/newParticle.json")
       var data = FileUtils.readFile(fileName)
       contentText += "\nData:\n" + data

       status.text += contentText

       var jsonObj = JSON.parse(data)

       status.text += "\n\nRead property jsonObj.subObject.data:\n" +
           jsonObj.subObject.subData
     }
   }
 }

Property Documentation

[read-only] searchPaths : list<string>

This read-only property returns the current list of paths getMultiPathUrl() uses to find a URL. The order of this list determines the search order: the path with index 0 is searched first, then index 1 and so on.

To modify the searchPaths list property use the function addSearchPath().

By default, the searchPaths contains the Documents directory

See also addSearchPath(), removeSearchPath(), and getMultiPathUrl().


Method Documentation

url addSearchPath(string absoluteSearchPath, int searchPathIndex)

Adds absoluteSearchPath to the searchPaths list property. The absoluteSearchPath must start with a "/" on Linux-based platforms and with C:\ or another valid drive letter on Windows. To receive the absolute path to one of the supported Storage Location directories, use storageLocation().

If no searchPathIndex is supplied, the absoluteSearchPath is appended to the end of the searchPaths property. This means it gets searched after all other searchPaths. You can define the order of the insertion by setting the searchPathIndex to anything between 0 and the size of the array.

See also getMultiPathUrl(), removeSearchPath(), and searchPaths.


bool copyFile(string source, string destination)

Copy a file given by the source path to the destination path.

Both paths can either be absolute or relative to the DocumentsLocation.

This function is shorthand for reading the file's text contents with readFileBytes() and then writing back with writeFile().

Note: The method does not use the platform's copy command. Thus it can also copy files from app assets (assets:/) and Qt resources (qrc:/).

Returns result

See also readFile(), writeFile(), listFiles(), and removeDir().


string cropPathAndKeepFilename(string filePath, bool cropFileExtension)

Returns the file name of the file at filePath.

This removes the directory from the path and keeps just the file name. If the optional parameter cropFileExtension is true, the file's extension is also removed.

Example usage:

 //returns "file.txt"
 var fileName = FileUtils.cropPathAndKeepFilename("/path/to/file/file.txt")

 //returns "file"
 var fileNameWithoutExtension = FileUtils.cropPathAndKeepFilename("/path/to/file/file.txt", true)

See also stripSchemeFromUrl(), getUrlByAddingSchemeToFilename(), and getAbsolutePathFromUrlString().


string defaultWritablePath()

A default writable directory used for relative paths inside most FileUtils functions. This is the same as calling storageLocation(FileUtils.DocumentsLocation).

See also storageLocation().


string engineBasePath()

Returns the base path of the QML engine. This is the file path to the initial QML file that loads your app or game.

See also engineBaseUrlPath() and qmlEngineBaseUrlForObject().


string engineBaseUrlPath()

Returns the base path of the QML engine as a file://, assets:/ or qrc:/ URL. This is the file path to the initial QML file that loads your app or game.

See also engineBasePath().


bool existsFile(string filePath)

Returns true if the file at filePath exists.

Note: This checks for the file using findFileOrDirectoryIncludingResources. To only check for the absolute filePath itself, use existsFileWithoutAdoptions().

See also existsFileFromUrl(), existsFileWithoutAdoptions(), and findFileOrDirectoryIncludingResources().


bool existsFileFromUrl(url fileUrl)

Returns true if the file at fileUrl exists.

URLs with the file:// scheme are supported.

Note: This only checks for absolute file URLs. To check for relative paths as well, use existsFile().

See also existsFile().


bool existsFileWithoutAdoptions(string filePath)

Returns true if the file at filePath exists.

Note: This only checks for absolute file paths. To check for relative paths as well, use existsFile().

See also existsFile().


string findFileOrDirectoryIncludingResources(string filePath)

Returns the absolute path to a file at filePath, if it exists.

filePath can either be an absolute path, or a path relative to the engineBasePath(). This works for both loading QML files from the file system and from QRC resources.

The return value is an absolute path if any file could be found. Otherwise it is an empty string.


string getAbsolutePathFromUrlString(string filePath)

Returns the absolute path to the directory of the file at filePath.

This removes the protocol scheme and the file name.

See also stripSchemeFromUrl(), getUrlByAddingSchemeToFilename(), and cropPathAndKeepFilename().


string getBasePath(QtObject sourceObject)

Returns the base path of the given sourceObject as string.

You can pass a QML object and retrieve the folder its QML file is located in. This can be used with getPathUrl() to load files located in the same folder as other QML files.

See also getPathUrl().


url getMultiPathUrl(url fileUrl, QtObject contextObject)

Returns a valid URL to a file using the searchPaths. This method looks up the file represented by fileUrl in each search path, in order.

If fileUrl is an absolute URL, the method looks up this absolute path first. If this file does not exist, it searches for the file name of the URL in the searchPaths.

If it is a relative URL, it appends it to each search path to check if that file exists. You can supply a contextObject, it looks up this object's getBasePath() as absolute path before the searchPaths. You can also omit contextObject, in this case it uses the engineBasePath() as context path.

If it finds any file this way, it returns a valid absolute URL to this file. If it can't find any file, in neither of the searchPaths and also not in the absolute provided location, it returns an empty URL.

You can call this function with DownloadableResource, which automatically registers its storagePath as search path. Thus you can use downloaded and extracted files with getMultiPathUrl().

The following example looks for an image called "testImage.png" in the app directory, i.e. in the same folder as the qml file. If it does not exist there, it searches in the Documents directory and in all searchPaths.

 import QtQuick
 import Felgo

 GameWindow {

   Scene {
     id: scene

     Image {
       // if found in the folder of this qml file then use the image from the FileUtils.ApplicationsLocation
       // if not found in the ApplicationsLocation, search for it in the DocumentsLocation and then in the searchPaths
       source: FileUtils.getMultiPathUrl("testImage.png", scene)
     }

   }
 }

See also addSearchPath(), removeSearchPath(), and searchPaths.


url getPathUrl(string filePath, var source)

Returns the full URL to the path of source and the appended relative filePath.

source can either be a QML object or an absolute URL or file path. If source is an object, the path used is the absolute path to its QML file using getBasePath().

Following example displays an image located in the same folder as some other QML file:

 import QtQuick
 import Felgo

 import "subdirectory"

 GameWindow {

   Scene {
     id: scene

     // SomeObject.qml is located in another directory
     SomeObject {
       id: someObject
     }

     // someImage.png is in the same directory as SomeObject.qml
     Image {
       source: FileUtils.getPathUrl("someImage.png", someObject)
     }
   }
 }

If source is a URL or a string, the path used is source itself. You can retrieve absolute paths with storageLocation() or getMultiPathUrl().

When filePath is "first-image.png" and the source is "file://somePath/particles/second-image.png" it returns "file://somePath/particles/first-image.png".

Following example lists all files from the source folder of the initialValue (../assets/img/). Afterwards it adds the returned names to the source path of the initialValue. Now the file paths in the files array can be used by components in other QML files to load the images without using relative paths which would not work in other QML files.

 import QtQuick
 import Felgo

 GameWindow {

   Scene {
     id: scene

     property url initialValue: "../assets/img/stars.png"

     Component.onCompleted: {
       // list image files in the directory of the source image.
       var stringList = FileUtils.listFiles(initialValue, ["*.png"])
       // fire.png, water.png, ...

       // Create file list with all images
       var files = []
       for(var i = 0; i < stringList.length; i++){
         // get a path from the initialValue and adds the names of the image list
         // ../assets/img/fire.png, ../assets/img/water.png, ...
         var fileurl = FileUtils.getPathUrl(stringList[i], initialValue)
         files[i] = fileurl
       }
       console.debug(JSON.stringify(files))
     }
   }
 }

See also listFiles(), storageLocation(), getMultiPathUrl(), and getBasePath().


url getUrlByAddingSchemeToFilename(string filePath)

Returns the filePath as a file://, assets:/ or qrc:/ URL.

See also stripSchemeFromUrl(), stripSchemeFromUrl(), and cropPathAndKeepFilename().


list<string> listFiles(url path, list<string> nameFilter)

Lists and returns files from a path depending on the nameFilter containing an array of strings. If no name filter was used all files are listed in the defined location.

The path contains the relative or absolute path. If path is relative, the files are listed in the DocumentsLocation directory.

The name filter may define which files should be listed. Following example lists all files with .json and .txt file ending. The files are listed from the directory of the current QML file.

To list all files in the Documents directory, use a relative path.

 import QtQuick
 import Felgo

 GameWindow {
   id: window

   Scene {
     id: scene

     Component.onCompleted: {
       // this will return ["config.json"], as a config.json file is placed in the same directory as the main.qml file
       var stringList = FileUtils.listFiles(Qt.resolvedUrl("."), ["*.json", "*.txt"])
       console.log("All .json and .txt files in app:\n" + stringList.join(", "))

       // this will return all files in the FileUtils.DocumentsLocation
       stringList = FileUtils.listFiles(".", ["*.json", "*.txt"])
       console.log("All .json and .txt files in documents:\n" + stringList.join(", "))
     }
   }
 }

For a more detailed example read Write, List, Read Files.

See also readFile() and writeFile().


bool openFile(string fileName)

Opens the file or directory fileName with an external application. This is the same as calling NativeUtils::openUrl() with a file:// URL.

The parameter fileName can be an absolute or relative file or directory path. In this case it creates the URL by calling getUrlByAddingSchemeToFilename(). It can also be of url type with the file:// protocol.

If fileName points to a directory, it opens the directory in the default file browser. If fileName points to a file, it opens the file with the default app associated with the file type, if one exists.

Use this example code to open a file called pdf-test.pdf from the app assets with the default PDF viewer. The PDF file is located relative to the current QML file:

 import Felgo
 import QtQuick

 App {
   id: app

   Component.onCompleted: {
     FileUtils.openFile(Qt.resolvedUrl("../assets/pdf-test.pdf"))
   }
 }

The following example uses DownloadableResource to download a PDF file to the user's documents directory. It then opens it with the default PDF viewer:

 import Felgo
 import QtQuick

 App {
   id: app

   DownloadableResource {
     source: "http://www.orimi.com/pdf-test.pdf"
     storageLocation: FileUtils.DocumentsLocation
     storageName: "pdf-test.pdf"
     extractAsPackage: false

     Component.onCompleted: {
       if(status === DownloadableResource.UnAvailable) {
         download()
       } else {
         openDownloadedFile()
       }
     }

     onStatusChanged: openDownloadedFile()

     function openDownloadedFile() {
       if(status === DownloadableResource.Available) {
         FileUtils.openFile(storagePath)
       }
     }
   }
 }

This method returns true if the file was opened successfully. It returns false if the platform cannot open this file type or directory.

Note: Depending on the platform, no file browser to open directories or app to open a specific file type may be installed. In this case, the call does nothing and returns false. Specifically, mobile platforms don't generally have file browsers for opening directories installed.

Note: To be able to open file:// URLs with another app on Android, if your targetSdkVersion in AndroidManifest.xml is 24 or higher, you need to enable the paths you wish to use in android/res/xml/file_paths.xml. Find detailed instructions here: Requirements for Reading Files on Android


string qmlEngineBaseUrlForObject(var object)

Returns the base path of the object's QML engine. This is the QML file path to the root of object's QML tree.

If object is in the same QML context as the current QML file, this is the same as engineBasePath().

See also engineBasePath().


string readFile(string fileName)

Reads a text file from fileName and returns the content of the file as string. If no file was found or an error occurred, it returns an empty string.

The fileName parameter contains the name with extension and its relative or absolute path. If the path is relative, the file is read relative to the DocumentsLocation directory.

Following code reads a file from a subfolder in the application directory. It then reads a file from a subfolder of the Documents directory:

 import QtQuick
 import Felgo

 GameWindow {
   id: window

   Scene {
     id: scene

     // URL property is relative to this QML file
     property url configFile: "subfolder/file.json"

     Component.onCompleted: {
       var relativeData = FileUtils.readFile(configFile)
       // alternatively you can also call it directly, but you need Qt.resolvedUrl()
       // var data = FileUtils.readFile(Qt.resolvedUrl("subfolder/file.json"))
       console.log(relativeData)

       // this file name is relative to FileUtils.Documents
       var documentsData = FileUtils.readFile("subfolder/file.json")
       console.log(documentsData)
     }
   }
 }

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

For a more detailed example see the section Write, List, Read Files.

See also readFileBytes(), readFileBase64(), writeFile(), copyFile(), listFiles(), and removeDir().


[since Felgo 4.2.0] var readFileBase64(string fileName)

Reads a binary file from fileName and returns the content of the file as a base64 encoded string. If no file was found or an error occurred, it returns an empty string.

The fileName parameter contains the name with extension and its relative or absolute path. If the path is relative, the file is read relative to the DocumentsLocation directory.

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

For additional information see the section Write, List, Read Files.

The following example reads an image file in Base64 encoding and passes the data to AppImage for display. This is only for demonstration purposes. In an actual project you would e.g. upload the Base64 data to a backend or run other custom processing.

 import Felgo
 import QtQuick

 App {
   NavigationStack {
     AppPage {
       title: "Base64 Example"

       Column {
         anchors {
           left: parent.left
           right: parent.right
           margins: dp(30)
         }

         AppImage {
           id: img
           width: parent.width
           height: width
           fillMode: Image.PreserveAspectFit
           anchors.horizontalCenter: parent.horizontalCenter
         }

         AppButton {
           text: "Read Base64"
           anchors.horizontalCenter: parent.horizontalCenter
           onClicked: {
             let fileLocation = FileUtils.storageLocation(FileUtils.DocumentsLocation, "felgo-logo.png")
             let dataBase64 = FileUtils.readFileBase64(fileLocation)
             img.source = "data:image/png;base64," + dataBase64
           }
         }
       }
     }
   }
 }

This method was introduced in Felgo 4.2.0.

See also readFile(), writeFile(), copyFile(), listFiles(), and removeDir().


[since Felgo 3.7.1] var readFileBytes(string fileName)

Reads a binary file from fileName and returns the content of the file as byte buffer. If no file was found or an error occurred, it returns an empty buffer.

The fileName parameter contains the name with extension and its relative or absolute path. If the path is relative, the file is read relative to the DocumentsLocation directory.

Following code reads a file from a subfolder in the application directory. It then reads a file from a subfolder of the Documents directory:

 import QtQuick
 import Felgo

 GameWindow {
   id: window

   Scene {
     id: scene

     // URL property is relative to this QML file
     property url imageFile: "subfolder/file.jpeg"

     Component.onCompleted: {
       var relativeData = FileUtils.readFileBytes(configFile)
       // alternatively you can also call it directly, but you need Qt.resolvedUrl()
       // var data = FileUtils.readFileBytes(Qt.resolvedUrl("subfolder/file.jpeg"))
       console.log("Image file size: " + relativeData.byteLength)

       // this file name is relative to FileUtils.Documents
       var documentsData = FileUtils.readFile("subfolder/file.jpeg")
       console.log("Image file size: " + documentsData.byteLength)
     }
   }
 }

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

For a more detailed example see the section Write, List, Read Files.

This method was introduced in Felgo 3.7.1.

See also readFile(), writeFile(), copyFile(), listFiles(), and removeDir().


bool removeDir(string dirName)

Removes the directory at dirName recursively with all contained files and sub-directories.

dirName can be an absolute path or a path relative to DocumentsLocation.

Returns true if the directory was removed successfully or if it did not exist before calling the method. Returns false if an existing directory could not be removed.

See also removeFile(), readFile(), writeFile(), listFiles(), and copyFile().


[since Felgo 3.7.1] bool removeFile(string fileName)

Removes the file at fileName.

fileName can be an absolute path or a path relative to DocumentsLocation.

Returns true if the file was removed successfully or if it did not exist before calling the method. Returns false if an existing file could not be removed.

This method was introduced in Felgo 3.7.1.

See also removeDir(), readFile(), writeFile(), listFiles(), and copyFile().


url removeSearchPath(string absoluteSearchPath)

Removes the search path absoluteSearchPath from the searchPaths property. All occurrences of the path are removed.

See also getMultiPathUrl(), addSearchPath(), and searchPaths.


bool saveImage(string fileName, QImage image, int quality)

Writes image to a file at fileName. Returns true if the image was written or false otherwise.

The fileName contains the name with extension and its relative or absolute path. If fileName is relative, the file is written relative to the DocumentsLocation directory.

The image must be of type QImage. To save an image from binary data, use writeFile().

An example usecase is to save the result from Item::grabToImage() with a custom quality:

 Rectangle {
   id: source
   width: 100
   height: 100
   gradient: Gradient {
       GradientStop { position: 0; color: "steelblue" }
       GradientStop { position: 1; color: "black" }
   }
 }

Then call:

 source.grabToImage(function(result) {
   // result.saveToFile("something.jpg"); --> This would compress with a default quality of about 75
   FileUtils.saveImage("something.jpg", result.image, 100); // Uses quality 100
 });

The quality parameter is optional. If provided it must be a value between 0 and 100. If no quality is provided, a platform and format dependent default quality is used.

To write a file to one of the Storage Locations, use storageLocation() for the fileName.

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

See also writeFile().


string storageLocation(enumeration location, string path)

Returns a writable file path for the specified location represented by one of the Storage Location enum constants using QStandardPaths::writableLocation(). The supported locations depend on the platform. Some might not be available on each platform. The function storageLocation() will then return an empty path.

The optional parameter path is a relative path appended to the storage location. You can also omit path, then the function returns the absolute path to the storage location itself.

For example, you can display an image stored in <Download directory>/_packages/myPackage/myImage.png:

 Image {
   source: FileUtils.storageLocation(FileUtils.DownloadLocation, "_packages/myPackage/myImage.png")
 }

This function ensures that the requested directory exists. If it does not exist it is created automatically. If the directory cannot be created, an empty string is returned.

See also defaultWritablePath().


string storageLocationDisplayName(enumeration location)

Returns a textual representation for the specified location represented by one of the Storage Location enum constants using QStandardPaths::displayName().


string stripSchemeFromUrl(var fileUrl)

Returns the fileUrl without the protocol scheme.

The parameter fileUrl can either be of string or URL type.

See also getUrlByAddingSchemeToFilename(), stripSchemeFromUrl(), and cropPathAndKeepFilename().


bool writeFile(string fileName, var fileData)

Writes fileData to a file at fileName. Returns true if the file could be written or false otherwise.

The fileName contains the name with extension and its relative or absolute path. If fileName is relative, the file is written relative to the DocumentsLocation directory.

The fileData can either be a string or a byte buffer. You can thus use any text or binary data. For example, you can use data you previously obtained with readFileBytes().

Note: To copy a file, you can use copyFile() instead.

To write a file to one of the Storage Locations, use storageLocation() for the fileName.

Following code writes a file with a relative path to the Documents directory:

 var success = FileUtils.writeFile("TextFiles/myFile.txt", "test text")

Following code writes a file without a given sub-path directly to the Documents directory:

 var success = FileUtils.writeFile("myFile.txt", "test text")

Following code writes a file without a given sub-path to the Downloads directory:

 var fileName = FileUtils.storageLocation(FileUtils.DownloadLocation, "myFile.txt")
 var success = FileUtils.writeFile(fileName, "test text")

The default path of the Documents directory depends on the target platform. See Storage Location for more information.

For a more detailed example see the section Write, List, Read Files.

See also readFile(), copyFile(), listFiles(), and removeDir().


Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded