html5 本地文件系统,本地文件系统 客户端存储 WebAPI编程 [HTML5知典]
本地文件系統(tǒng)
首先要聲明的是,這里的本地文件系統(tǒng)并不是客戶端操作系統(tǒng)下的本地磁盤文件系統(tǒng),而是Web應(yīng)用程序在客戶端創(chuàng)建和管理的一個(gè)與頁(yè)面相關(guān)聯(lián)的沙盒文件系統(tǒng)。
概述
本地文件系統(tǒng)(Local FileSystem)API是通過FileSystem對(duì)象和window.requestFileSystem()方法來實(shí)現(xiàn)的。
Web應(yīng)用程序可以通過調(diào)用window.requestFileSystem()來請(qǐng)求對(duì)一個(gè)沙盒文件系統(tǒng)的訪問權(quán)限。調(diào)用requestFileSystem()會(huì)創(chuàng)建一個(gè)新的沙盒存儲(chǔ)空間。成功調(diào)用之后會(huì)返回一個(gè)FileSystem對(duì)象。
代碼示例
請(qǐng)求文件系統(tǒng)
通過調(diào)用window.requestFileSystem()請(qǐng)求對(duì)沙盒文件系統(tǒng)的訪問權(quán)限:
//瀏覽器的兼容性
window.requestFileSystem = window.requestFilsSystem || window.webkitRequestFileSystem;
window.requestFileSystem(type, size, successCallback, opt_errorCallback);
下面對(duì)調(diào)用requestFileSystem()時(shí)傳遞的參數(shù)作個(gè)簡(jiǎn)單的介紹:
* type \\ 文件存儲(chǔ)是否持久。可為PERSISTENT,TEMPORARY。通過TEMPORARY存儲(chǔ)的數(shù)據(jù)可由瀏覽器自行決定刪除。要請(qǐng)求PERSISTENT存儲(chǔ),必須獲得用戶或應(yīng)用的明確授權(quán),并需要用戶向應(yīng)用授予配額。
* size \\存儲(chǔ)空間大小(以字節(jié)為單位)。
* successCallback \\ 文件系統(tǒng)請(qǐng)求成功時(shí)調(diào)用的回調(diào)函數(shù)。其參數(shù)為FileSystem對(duì)象。
* opt_errorCallback \\ 用于處理錯(cuò)誤或獲取文件系統(tǒng)的請(qǐng)求遭到拒絕時(shí)可選的回調(diào)。其參數(shù)為FileError對(duì)象。
創(chuàng)建文件夾
fileSystem.root.getDirectory('Hudao', {create: true}, function(dirEntry) {
console.log('The directory'name is '+ dirEntry.name);
}, opt_errorCallback);
上面例子中,在根目錄中創(chuàng)建一個(gè)文件夾。getDirectory()方法用來讀和創(chuàng)建目錄。該方法第一個(gè)參數(shù)可以傳遞一個(gè)名字或者路徑來創(chuàng)建。
創(chuàng)建文件
fileSystem.root.getFile('hudao.txt', {create: true, exclusive: true}, function(fileEntry) {
console.log('The file's name is '+fileEntry.name);
}, opt_errorCallback);
上面例子中在根目錄下創(chuàng)建一個(gè)空的文件hudao.txt。getFile()方法用來讀和創(chuàng)建文件。
拷貝文件
function copy(currentDirec, srcEntry, destDir) {
currentDirec.getFile(srcEntry, {}, function(fileEntry) {
currentDirec.getDirectory(destDir, {}, function(dirEntry) {
fileEntry.copyTo(dirEntry);
}, errorHandler);
}, errorHandler);
}
copy(fileSystem.root, 'hudao.txt', 'Documents/');
上面的例子拷貝hudao.txt從ROOT到Document目錄下。
移動(dòng)文件
function move(currentDirec, srcEntry, directoyName) {
currentDirec.getFile(srcEntry, {}, function(fileEntry) {
currentDirec.getDirectory(directoryName, {}, function(dirEntry) {
fileEntry.moveTo(dirEntry);
}, errorHandler);
}, errorHandler);
}
move(fileSystem.root, 'hudao.txt', 'Documents/');
上面的例子是移動(dòng)hudao.txt到Document的目錄下。
重命名文件
function rename(currentDirec, srcEntry, newName) {
currentDirec.getFile(srcEntry, {}, function(fileEntry) {
fileEntry.moveTo(currentDirec, newName);
}, errorHandler);
}
rename(fileSystem.root, 'hudao.txt', 'hudaokeji.txt');
上面的例子是將hudao.txt重命名成hudaokeji.txt。
參考
總結(jié)
以上是生活随笔為你收集整理的html5 本地文件系统,本地文件系统 客户端存储 WebAPI编程 [HTML5知典]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爬取2019年央视新闻APP
- 下一篇: OKLink区块链浏览器连续升级,欧科云