File: Managing Files
This tutorial demonstrates how you can control files and directories on the device, and access the sandboxed sections of a local file system to search, create, or delete a directory or file.
Warm-up
Become familiar with the File API basics by learning about:
- Local files
-
Reading Local File Information
Access and read local file information.
-
Reading Local File Content
Access, read, and display a local image file.
-
Slicing Blob
Read a local file as a binary string and slice it.
-
Reading Local File Information
- Sandboxed file system in mobile applications
-
Accessing a Sandboxed File System
Request access to sandboxed sections of a local file system.
-
Displaying Files in a Sandboxed File System
Display entries (directories or files) in sandboxed sections of a local file system.
-
Creating a Directory or File
Create a directory or file in a sandboxed section of a local file system.
-
Removing a Directory or File
Delete the directory or file in a sandboxed section of a local file system.
-
Accessing a Sandboxed File System
Reading Local File Information
Reading basic information, such as file name, size, MIME type, modification date, and path, of a local file is a useful file management skill:
- To display file information, create the <input type="file"> element and other needed elements:
<input type="file" id="tizenFiles" onchange="readSelectedFiles();" multiple /> <div id="selectedFileInfoList"></div>
Note To enable multiple upload, use the multiple attribute. - Create a FileList instance:
<script> var files = document.getElementById("tizenFiles").files; if (files.length === 0) return; </script>
- Use the readSelectedFiles() method of the FileList interface to retrieve and display file information, such as file name, size, MIME type, and modification date:
<script> function readSelectedFiles() { var displaySection = document.getElementById('selectedFileInfoList'); var html = []; for (var i = 0; i < files.length; i++) { var file = files[i]; html.push("<li>", "<strong>", escape(file.name), "</strong><br />", " type: ", file.type, "<br />", /* MIME type */ " size: ", file.size, "bytes<br />", /* Size */ " lastModifiedDate: ", /* Last modification date */ (file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : ""), " <br />", "</li>"); } displaySection.innerHTML = "<ul>" + html.join("") + "</ul>"; } </script>
Figure: Displaying file information (in mobile applications only)
Source Code
For the complete source code related to this use case, see the following file:
Reading Local File Content
Reading a local image file in a Web application is a useful file management skill:
- To read a local image file and display its information, create the <input type="file"> element and other needed elements:
<input type="file" id="tizenFiles" onchange="readSelectedFiles();" multiple/> <div id="selectedFileInfoList"></div>
- Create a FileReader instance to read the content of the local image file. Use the readAsDataURL() method to read data in the dataURL format.
If the data is loaded, an onload event is fired. Create an img element to allocate the event result property value for rendering:
<script> function readSelectedFiles() { var files = document.getElementById("tizenFiles").files; if (files.length === 0) { return; } var html = []; for (var i = 0; i < files.length; i++) { var file = files[i]; var reader = new FileReader(); /* Check whether the file is an image */ if (!file.type.match("image.*")) { continue; } reader.onload = (function(e) { var img = document.createElement("img"); img.src = e.target.result; /* Set the selected image's dataURL */ img.title = escape(file.name); img.className = "img"; document.getElementById("selectedFileInfoList").appendChild(img); }; reader.readAsDataURL(file); } } </script>
Figure: Displaying an image file (in mobile applications only)
Source Code
For the complete source code related to this use case, see the following file:
Slicing Blob
Slicing a local file using the Blob interface is a useful file management skill:
- Create the <input type="file"> element, the element for inputting the start byte and the end byte for slice, and the element for displaying the slicing result:
<input type="file" id="tizenFile" name="tizenFile" onchange="setFileSize();" /> <br /> start byte: <input type="text" id="startByte" name="startByte" style="width: 100px;" />~ end byte: <input type="text" id="endByte" name="endByte" style="width: 100px;" /> <input type="button" value="Slice File" onclick="readBinaryString();" /> <div id="result" style="padding: 25px 10px 0 20px;"></div>
- To read the local file, create a FileReader instance:
<script> var reader = new FileReader(); </script>
- Slice the defined byte range (from startByte to endByte) using the slice() method of the File interface:
<script> function readBinaryString() { if (document.getElementById("tizenFile").files.length === 0) { alert("Upload File"); return; } var file = document.getElementById("tizenFile").files[0]; var startByte = document.getElementById("startByte").value; var endByte = document.getElementById("endByte").value; var blob = file.slice(startByte, endByte);
A new Blob object is created.
-
Read the data as a binary string using the readAsBinaryString() method:
reader.readAsBinaryString(blob); } </script>
- If the data loading is complete, the read data is displayed. Check the status using the onloadend event:
<script> reader.onloadend = function(e) { if (e.target.readyState == FileReader.DONE) /* DONE == 2 */ { document.getElementById('result').textContent = e.target.result; } }; </script>
Figure: Slicing a file (in mobile applications only)
Source Code
For the complete source code related to this use case, see the following file:
Accessing a Sandboxed File System
Requesting access to sandboxed sections of a local file system is a useful file management skill:
- Use the requestFileSystem() method of the LocalFileSystem interface to request access to sandboxed sections of a local file system:
<script> /* Tizen uses the webkit prefix */ window.requestFileSystem = window.webkitRequestFileSystem; var fs = null; /* Initialize the file system when loading a page */ if (window.requestFileSystem) { initFS(); } function initFS() { /* Request for access to the sandboxed file system */ /* and define PERSISTENT or TEMPORARY storage */ window.requestFileSystem(window.TEMPORARY, 1024 * 1024, /* Storage space (bytes) */ function(filesystem) {fs = filesystem;}, errorHandler); } </script>
Note The requestFileSystem() method is created in the Web application program when it is initially called. The directory file in the file system root can be searched, created and deleted by accessing local file system.
Source Code
For the complete source code related to this use case, see the following file:
Displaying Files in a Sandboxed File System
Reading a file or directory in a sandboxed section of a local file system is a useful file management skill:
- Create the <input type="button"> element for displaying the entries (directories or files) stored in the root directory within the file system, and the list element for displaying the result:
<input type="button" value="Show FileList" onclick="ShowFileList();" /> <ul id="resultSection"></ul>
- To read the entry within the file system, use the createReader() method of the DirectoryEntry interface:
<script> function ShowFileList() { if (!fs) return; var objResultSection = document.querySelector('#resultSection'); var root = fs.root; var dirReader = root.createReader();
- Use the readEntries() method of the DirectoryReader interface to read all entries:
dirReader.readEntries(function(entries) {
- Display the list of the relevant entries using the Entry interface:
if (!entries.length) { objResultSection.innerHTML = 'Filesystem is empty.'; } else { var fragment = document.createDocumentFragment(); var entry, i; for (i = 0; i < entries.length; i++) { entry = entries[i]; var img = entry.isDirectory ? '<img class="icon-img" src="img/icon_folder.png" alt="folder">' : '<img class="icon-img" src="img/icon_file.png" alt="file">'; var li = document.createElement('li'); /* Display entry name */ li.innerHTML = [img, '<span>', entry.name, '</span>'].join(''); objResultSection.innerHTML = ''; fragment.appendChild(li); } objResultSection.appendChild(fragment); } }, errorHandler); } </script>
Note |
---|
For error handling, see Accessing a Sandboxed File System. |
Figure: Displaying files
Source Code
For the complete source code related to this use case, see the following files:
Creating a Directory or File
Creating a directory or file in a sandboxed section of a local file system is a useful file management skill:
- Create the select element for selecting the type of entry to be added, <input type="text"> element for entering the entry name, and <input type="button>" element for creating the entry:
<select id="selType"> <option value="dir">Directory</option> <option value="file">File</option> </select> <input type="text" id="txtName" name="txtName" style="width: 200px;" maxlength="20" /> <input type="button" value="Add File or Directory" onclick="AddFile();" />
- To create a directory, use the getDirectory() method. To create a file, use the getFile() method:
<script> function AddFile() { if (!fs) return; var type = document.querySelector('#selType').value; var name = document.querySelector('#txtName').value; if (name == "") { return alert("Enter File or Directory Name."); } if (type == "file") { /* Create file */ fs.root.getFile(name, {create: true}, null, errorHandler); } else if (type == "dir") { /* Create directory */ fs.root.getDirectory(name, {create: true}, null, errorHandler); } document.querySelector('#resultSection').innerHTML = 'Files created.'; } </script>
Note For error handling, see Accessing a Sandboxed File System. Figure: Adding a file
Source Code
For the complete source code related to this use case, see the following file:
Removing a Directory or File
Deleting a directory or file in a sandboxed section of a local file system is a useful file management skill:
- Create the <input type="button"> element for deleting the entry (directory or file):
<input type="button" value="Remove all files" onclick="RemoveFile();" />
- To delete a directory and all the files in it, use the removeRecursively() method. To delete an individual file, use the remove() method:
<script> function RemoveFile() { if (!fs) return; var dirReader = fs.root.createReader(); var entry, i; dirReader.readEntries(function(entries) { for (i = 0; i < entries.length; i++) { entry = entries[i]; if (entry.isDirectory) { entry.removeRecursively(function() {}, errorHandler); } else { entry.remove(function() {}, errorHandler); } } document.querySelector('#resultSection').innerHTML = 'Directory emptied.'; }, errorHandler); } </script>
Note For error handling, see Accessing a Sandboxed File System. Figure: Deleting files
Source Code
For the complete source code related to this use case, see the following file: