search
HomeWeb Front-endH5 TutorialIntroduction to the use of HTML5 FileSystem API_html5 tutorial skills

One of the strengths of HTML5 is that it allows web programs to apply for some temporary or permanent space (Quota) where data storage and even file operations can be performed.

FileSystem provides operations such as creating, moving, and deleting folders and files, which greatly facilitates local processing of data. Moreover, all data is in a sandbox (sandboxed), and different web programs cannot access each other. This This ensures data integrity and security.

In the CatWrite project, this feature of HTML5 is used to store data, which is very convenient. However, currently only the Chrome browser supports the FileSystem API better, so it can only run in the Chrome browser.

When completing this function, I consulted a lot of information. Some of the information was a year ago. However, with the changes in browser versions, some codes have become outdated. I will summarize and organize them one by one here. Only the APIs used in the project are listed here, which is a summary of the completed functions.

Apply for space
In order to store data, you must apply to the browser. If it is permanent storage, the user will be asked, and execution will continue only after consent.

First you must declare the desired permissions.

Copy code
The code is as follows:

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; //File system request identification
window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL; //Obtain the read permission of the file based on the URL

After obtaining the system permission You can apply for space from the browser

Copy the code
The code is as follows:

window. requestFileSystem(window.PERSISTENT, //persistent(permanent) or temporary(temporary)
1024*1024, //1M
onInitFs, //callback function after success
errorHandler); //after error Callback function

Callback function

Copy code
The code is as follows:

function onInitFs(fs){
fs.root.getDirectory('catwrite_documents', {create: true}, function(dirEntry) {
console.log('You have just created the ' dirEntry. name ' directory.');
}, errorHandler);
}
//Error callback
function errorHandler(err){
var msg = 'An error occured: ';
switch (err.code) {
case FileError.NOT_FOUND_ERR:
msg = 'File or directory not found';
break;
case FileError.NOT_READABLE_ERR:
msg = 'File or directory not readable';
break;
case FileError.PATH_EXISTS_ERR:
msg = 'File or directory already exists';
break;
case FileError.TYPE_MISMATCH_ERR:
msg = ' Invalid filetype';
break;
default:
msg = 'Unknown Error';
break;
};
console.log(msg err);
}

If you succeed, you will regret calling the OnInitFs callback function, and use the getDirectory method to create a folder, which will be discussed below.

But there is a problem. If you do this, it will be applied every time the page is loaded. This is definitely not what we want. What we want is to be able to read the data when there is data.

Determine whether space has been applied for
So we need to read the browser's data to see if it has been stored. This uses another API:

Copy the code
The code is as follows:

void queryUsageAndQuota(
in DOMString url,
in EntryCallback successCallback,
in optional ErrorCallback errorCallback
);

This API can query the space status of the current web, if successful The successCallback callback function will be called and the used space and total space will be passed into the method as parameters. If it fails, errorCallback is called.

Copy code
The code is as follows:

window.webkitStorageInfo.queryUsageAndQuota(webkitStorageInfo.PERSISTENT,
function(used, remaining){
if(remaining == ""){
console.log("No space applied. ");
}else{
console.log("used space" used);
console.log("all space" remaining);
}
},
errorHandler);


We can judge whether there is application space by judging the remaining parameter. If there is no application, return to the previous step to apply for space. If there is already space, you need to obtain the space and the file so that you can operate the data.

Get file entry
FileSystem uses a special file system and sandbox mode. Files in the sandbox cannot be accessed on a computer or other web. You can only use the corresponding format. access.

Type in your browser:

?filesystem:http://catcoder.com/persistent/
 

In this way, you can access the permanent data of the catcoder.com website on this machine. Replace persistent with temporary to read the temporary space.

Then we can get the entry of the file through the URL and the corresponding API (Lets you look up the entry for a file or directory with a local URL).

Copy code
The code is as follows:

void resolveLocalFileSystemURL(
in DOMString url ,
in EntryCallback successCallback,
in optional ErrorCallback errorCallback
);

You can read the data stored on the machine below

Copy code
The code is as follows:

var url = "filesystem:http://" window. location.host "/persistent/catwrite_documents/";
window.resolveLocalFileSystemURL(url,function(fileEntry){
console.log(fileEntry);
var dirReader = fileEntry.createReader();
var readEntries = function(){
dirReader.readEntries(function(results){
if(!results.length){
create_file_title("Default file", "");
console.log ("No file!");
}else{
console.log("Read results.length "files");
for(var i = 0; i console.log(results[i].name);
getFileContentByName(fileEntry, results[i].name);
}
}
},errorHandler) ;
};
readEntries();
},errorHandler);
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor