$cordovaFile-file詳解


Cordova 提供了一個  file 插件,通過這個插件我們很方便地實現在各種設備下對文件、和文件夾進行訪問,編輯等各種操作。 

一、添加File插件
首先我們要在「終端」中進入工程所在的目錄,然後運行如下命令添加  file 插件:
1
cordova plugin add cordova-plugin-file

二、普通文件的讀取與寫入

1,文件寫入(持久化保存)
在iOS中,下面代碼會將文件寫入到  Documents 目錄(應用程序用戶文檔目錄)下:
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!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 文件創建成功,打開后里面內容也寫入成功。
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)


2,持久化文件保存路徑設置:iOS平臺
在  config.xml 文件中,我們可以配置修改持久話化文件保存位置( Persistent storage location)。
如何不配置的話,從前面樣例可以看到。默認是保存在程序的  Documents 文件目錄下,也就是如下配置:
1
< preference  name = "iosPersistentFileLocation"  value = "Compatibility"  />
但保存在這裏有個副作用,就是使用  iTunes 可以看到這些文件。如果要持久化保存很多文件,又不希望和普通用戶文件混起來。我們可以修改成如下配置:
1
< preference  name = "iosPersistentFileLocation"  value = "Library"  />
可以看到文件保存到應用的  Library 文件夾下了:
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)


3,持久化文件保存路徑設置:Android平臺
同樣的,我們也可以在  config.xml 文件中配置修改  Android 設備中持久化文件保存位置( Persistent storage location)。
如果不配置,或者進行如下配置的話。持久化文件是保存在  /data/data/<packageId> 下面。 
1
< preference  name = "AndroidPersistentFileLocation"  value = "Internal"  />
修改成如下配置的話,如果設備有SD卡(或等效的存儲分區)。那麼持久性文件將被存儲在該空間的根路徑下。
1
< preference  name = "AndroidPersistentFileLocation"  value = "Compatibility"  />

4,創建臨時文件(將文件寫入到臨時文件夾下)
在iOS系統中,下面代碼會將文件寫入到  tmp 目錄下。當系統空間不足或是資源不足的時候,臨時文件會被系統刪除。
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
同上面的樣例相比,這裏只改了一個地方(高亮處)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//創建並寫入文件
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)到末尾。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//將內容數據寫入到文件中(支持追加內容)
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);
     });
}
使用方式如下:
1
2
var  dataObj =  new  Blob([ '\n值得您每天來看看!' ], { type:  'text/plain'  });
writeFile(fileEntry, dataObj,  true );

6,讀取文件
下面將之前創建的  hangge.txt 文件中的內容讀取出來,並顯示。
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)

下面  readFile() 方法接收傳入的  FileEntry 對象,並讀取對象內容。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//讀取文件
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
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//創建並寫入文件
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,保存二進制文件
下面代碼從網絡上獲取一張圖片,並保存到本地。
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!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 元素中顯示。
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!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 圖片爲例:
原文:Cordova - file插件的使用詳解(文件的創建、讀寫,文件夾創建等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!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){
相關文章
相關標籤/搜索