1. 程式人生 > >file外掛的使用詳解(檔案的建立、讀寫,資料夾建立等)

file外掛的使用詳解(檔案的建立、讀寫,資料夾建立等)

Cordova 提供了一個 file 外掛,通過這個外掛我們很方便地實現在各種裝置下對檔案、和資料夾進行訪問,編輯等各種操作。 

一、新增File外掛
首先我們要在“終端”中進入工程所在的目錄,然後執行如下命令新增 file 外掛:
1 cordova plugin add cordova-plugin-file

二、普通檔案的讀取與寫入

1,檔案寫入(持久化儲存)
在iOS中,下面程式碼會將檔案寫入到 Documents 目錄(應用程式使用者文件目錄)下:
<!DOCTYPE html>
<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
            //建立並寫入檔案
            function createAndWriteFile(){
              //持久化資料儲存
              window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
 
                console.log('開啟的檔案系統: ' + fs.name);
                fs.root.getFile("hangge.txt", { create: true, exclusive: false },
                 function (fileEntry) {
 
                    console.log("是否是個檔案?" + fileEntry.isFile.toString());
                    // fileEntry.name == 'hangge.txt'
                    // fileEntry.fullPath == '/hangge.txt'
                    //檔案內容
                    var dataObj = new Blob(['歡迎訪問hangge.com'], { type: 'text/plain' });
                    //寫入檔案
                    writeFile(fileEntry, null);
 
                }, onErrorCreateFile);
 
              }, onErrorLoadFs);
            }
 
            //將內容資料寫入到檔案中
            function writeFile(fileEntry, dataObj) {
                //建立一個寫入物件
                fileEntry.createWriter(function (fileWriter) {
 
                    //檔案寫入成功
                    fileWriter.onwriteend = function() {
                        console.log("Successful file read...");
                    };
 
                    //檔案寫入失敗
                    fileWriter.onerror = function (e) {
                        console.log("Failed file read: " + e.toString());
                    };
                     
                    //寫入檔案
                    fileWriter.write(dataObj);
                });
            }
 
            //檔案建立失敗回撥
            function  onErrorCreateFile(error){
              console.log("檔案建立失敗!")
            }
 
            //FileSystem載入失敗回撥
            function  onErrorLoadFs(error){
              console.log("檔案系統載入失敗!")
            }
        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="createAndWriteFile();">建立並寫入檔案</button>
    </body>
</html>


可以看到 hangge.txt 檔案建立成功,開啟后里面內容也寫入成功。
2,持久化檔案儲存路徑設定:iOS平臺
在 config.xml 檔案中,我們可以配置修改持久話化檔案儲存位置(Persistent storage location)。
如何不配置的話,從前面樣例可以看到。預設是儲存在程式的 Documents 檔案目錄下,也就是如下配置:
<preference name="iosPersistentFileLocation" value="Compatibility" />

但儲存在這裡有個副作用,就是使用 iTunes 可以看到這些檔案。如果要持久化儲存很多檔案,又不希望和普通使用者檔案混起來。我們可以修改成如下配置:
<preference name="iosPersistentFileLocation" value="Library" />

可以看到檔案儲存到應用的 Library 資料夾下了:
3,持久化檔案儲存路徑設定:Android平臺
同樣的,我們也可以在 config.xml 檔案中配置修改 Android 裝置中持久化檔案儲存位置(Persistent storage location)。 如果不配置,或者進行如下配置的話。持久化檔案是儲存在/data/data/<packageId> 下面。 
<preference name="AndroidPersistentFileLocation" value="Internal" />

修改成如下配置的話,如果裝置有SD卡(或等效的儲存分割槽)。那麼永續性檔案將被儲存在該空間的根路徑下。
<preference name="AndroidPersistentFileLocation" value="Compatibility" />

4,建立臨時檔案(將檔案寫入到臨時資料夾下) 在iOS系統中,下面程式碼會將檔案寫入到 tmp 目錄下。當系統空間不足或是資源不足的時候,臨時檔案會被系統刪除。 同上面的樣例相比,這裡只改了一個地方(高亮處)。
//建立並寫入檔案
function createAndWriteFile(){
  //臨時資料儲存
  window.requestFileSystem(LocalFileSystem.TEMPORARY, 5 * 1024 * 1024, function (fs) {
 
    console.log('開啟的檔案系統: ' + fs.name);
    fs.root.getFile("hangge.txt", { create: true, exclusive: false },
     function (fileEntry) {
 
        console.log("是否是個檔案?" + fileEntry.isFile.toString());
        // fileEntry.name == 'hangge.txt'
        // fileEntry.fullPath == '/hangge.txt'
        //檔案內容
        var dataObj = new Blob(['歡迎訪問hangge.com'], { type: 'text/plain' });
        //寫入檔案
        writeFile(fileEntry, dataObj);
 
    }, onErrorCreateFile);
 
  }, onErrorLoadFs);
}

5,檔案末尾寫入新內容
下面改造下 writeFile() 方法,增加一個 isAppend 引數。用來表示資料寫入是完全覆蓋,還是追加(append)到末尾。
//將內容資料寫入到檔案中(支援追加內容)
function writeFile(fileEntry, dataObj, isAppend) {
    //建立一個寫入物件
    fileEntry.createWriter(function (fileWriter) {
 
        //檔案寫入成功
        fileWriter.onwriteend = function() {
            console.log("Successful file read...");
        };
 
        //檔案寫入失敗
        fileWriter.onerror = function (e) {
            console.log("Failed file read: " + e.toString());
        };
 
        //如果是最加內容,則定位到檔案尾部
        if (isAppend) {
            try {
                fileWriter.seek(fileWriter.length);
            }
            catch (e) {
                console.log("file doesn't exist!");
            }
        }
        fileWriter.write(dataObj);
    });
}

使用方式如下:
var dataObj = new Blob(['\n值得您每天來看看!'], { type: 'text/plain' });
writeFile(fileEntry, dataObj, true);

6,讀取檔案
下面將之前建立的 hangge.txt 檔案中的內容讀取出來,並顯示。
下面 readFile() 方法接收傳入的 FileEntry 物件,並讀取物件內容。
//讀取檔案
function readFile(fileEntry) {
    fileEntry.file(function (file) {
        var reader = new FileReader();
        reader.onloadend = function() {
            alert(this.result);
        };
        reader.readAsText(file);
    }, onErrorReadFile);
}
 
//讀取檔案失敗響應
function onErrorReadFile(){
  console.log("檔案讀取失敗!");
}


三、資料夾操作 下面程式碼在 Documents 目錄(應用程式使用者文件目錄)下建立子資料夾:assets/images
//建立並寫入檔案
function createAndWriteFile(){
  //臨時資料儲存
  window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
 
    console.log('開啟的檔案系統: ' + fs.name);
    fs.root.getDirectory('assets', { create: true }, function (dirEntry) {
        dirEntry.getDirectory('images', { create: true }, function (subDirEntry) {
            //createFile(subDirEntry, "hangge.txt");
        }, onErrorGetDir);
    }, onErrorGetDir);
 
  }, onErrorLoadFs);
}
 
//資料夾建立失敗回撥
function onErrorGetDir(error){
  console.log("資料夾建立失敗!")
}
 
//FileSystem載入失敗回撥
function  onErrorLoadFs(error){
  console.log("檔案系統載入失敗!")
}


四、二進位制檔案(binary file)操作 1,儲存二進位制檔案

下面程式碼從網路上獲取一張圖片,並儲存到本地。

<!DOCTYPE html>

<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
            //下載圖片
            function downloadImage(){
               
              window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
 
                console.log('開啟的檔案系統: ' + fs.name);
                getSampleFile(fs.root);
 
              }, onErrorLoadFs);
            }
 
            //獲取圖片
            function getSampleFile(dirEntry) {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'http://www.hangge.com/blog/images/logo.png', true);
                xhr.responseType = 'blob';
 
                xhr.onload = function() {
                    if (this.status == 200) {
                        var blob = new Blob([this.response], { type: 'image/png' });
                        saveFile(dirEntry, blob, "hangge.png");
                    }
                };
                xhr.send();
            }
 
            //儲存圖片檔案
            function saveFile(dirEntry, fileData, fileName) {
                dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
                    writeFile(fileEntry, fileData);
                }, onErrorCreateFile);
            }
 
            //將圖片資料寫入到檔案中
            function writeFile(fileEntry, dataObj, isAppend) {
              //建立一個寫入物件
              fileEntry.createWriter(function (fileWriter) {
 
                  //檔案寫入成功
                  fileWriter.onwriteend = function() {
                      console.log("Successful file write...");
                      if (dataObj.type == "image/png") {
                          readBinaryFile(fileEntry);
                      }
                      else {
                          readFile(fileEntry);
                      }
                  };
 
                  //檔案寫入失敗
                  fileWriter.onerror = function(e) {
                      console.log("Failed file write: " + e.toString());
                  };
 
                  //寫入檔案
                  fileWriter.write(dataObj);
              });
          }
 
          //檔案建立失敗回撥
          function  onErrorCreateFile(error){
            console.log("檔案建立失敗!")
          }
 
          //FileSystem載入失敗回撥
          function  onErrorLoadFs(error){
            console.log("檔案系統載入失敗!")
          }
        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="downloadImage();">下載圖片</button>
    </body>
</html>

2,讀取二進位制檔案
下面程式碼讀取前面下載下來的圖片(hangge.png),並在 image 元素中顯示。
<!DOCTYPE html>
<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
            //載入圖片
            function loadImage(){
               
              window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
 
                console.log('開啟的檔案系統: ' + fs.name);
                fs.root.getFile("hangge.png", { create: true, exclusive: false },
                 function (fileEntry) {
                    readBinaryFile(fileEntry);
                }, onErrorCreateFile);
 
              }, onErrorLoadFs);
            }
 
            //讀取圖片檔案
            function readBinaryFile(fileEntry) {
                fileEntry.file(function (file) {
                    var reader = new FileReader();
 
                    reader.onloadend = function() {
                        //載入成功顯示圖片
                        var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
                        displayImage(blob);
                    };
 
                    reader.readAsArrayBuffer(file);
 
                }, onErrorReadFile);
            }
 
            //顯示圖片
            function displayImage(blob) {
                var elem = document.getElementById('imageFile');
                elem.src = window.URL.createObjectURL(blob);
            }
 
            //檔案建立失敗回撥
            function  onErrorCreateFile(error){
              console.log("檔案建立失敗!")
            }
 
            //讀取檔案失敗響應
            function onErrorReadFile(){
              console.log("檔案讀取失敗!");
            }
 
            //FileSystem載入失敗回撥
            function  onErrorLoadFs(error){
              console.log("檔案系統載入失敗!")
            }
        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="loadImage();">載入圖片</button>
        <image id="imageFile"/>
    </body>
</html>


3,更便捷的顯示圖片辦法
要將裝置中的圖片顯示在頁面上,前面的樣例做法是先的到這個圖片的 FileEntry 物件,然後讀出出 Blob 資料,做最後將 Blob 資料通過 window.URL.createObjectURL() 方法建立個url傳遞給頁面的 img 元素 src
其實還有更簡單的辦法,得到圖片的 FileEntry 物件後,通過其 toURL() 方法即可將其 url 賦給 img 元素 src 屬性即可。

下面同樣以載入顯示 Documents 目錄下的 hangge.png 圖片為例:

<!DOCTYPE html>

<html>
    <head>
        <title>Capture Photo</title>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
            //載入圖片
            function loadImage(){
               
              window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
 
                console.log('開啟的檔案系統: ' + fs.name);
                fs.root.getFile("hangge.png", { create: true, exclusive: false },
                 function (fileEntry) {
                    displayImageByFileURL(fileEntry);
                }, onErrorCreateFile);
 
              }, onErrorLoadFs);
            }
 
            //顯示圖片
            function displayImageByFileURL(fileEntry) {
                var elem = document.getElementById('imageFile');
                elem.src = fileEntry.toURL();
            }
 
            //檔案建立失敗回撥
            function  onErrorCreateFile(error){
              console.log("檔案建立失敗!")
            }
 
            //FileSystem載入失敗回撥
            function  onErrorLoadFs(error){
              console.log("檔案系統載入失敗!")
            }
        </script>
    </head>
    <body style="padding-top:50px">
        <button style="font-size:23px;" onclick="loadImage();">載入圖片</button>
        <img id="imageFile"/>
    </body>
</html>

五、使用cdvfile protocol 更快捷地定位到檔案、資料夾

通過 cdvfile 協議,我們可以很方便的訪問裝置檔案、資料夾。

	
cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file

1,在 html 頁面中直接通過 cdvfile:// 路徑來載入檔案。

還是同上面樣例一樣,在頁面上顯示同一張圖片:
<img src="cdvfile://localhost/persistent/hangge.png" />
2,複製檔案 
下面將 Documents 目錄下的 hangge.png 複製到 tmp 目錄下,並改名為 temp.png 這裡通過 FileTransfer 物件的 copyTo() 方法進行復制,如果想要實現移動的話則改成 moveTo() 方法即可。
function copyFile(){
  window.resolveLocalFileSystemURL('cdvfile://localhost/persistent/hangge.png',
    function(fileEntry) {
 
      window.resolveLocalFileSystemURL('cdvfile://localhost/temporary',
        function(dirEntry) {
            fileEntry.copyTo(dirEntry, "temp.png", successCallback, errorCallback);
        },
              function(error){console.log("建立失敗!")});
 
    },
    function(error){console.log("建立失敗!")});
}
 
//檔案複製成功
function  successCallback() {
 console.log("檔案複製成功!")
}
 
//檔案複製失敗
function  errorCallback() {
 console.log("檔案複製失敗!")
}

原文出自:www.hangge.com  原文連結:http://www.hangge.com/blog/cache/detail_1179.html