2016-03-28 28 views
0

我想使用readAsText ngCordova插件從CSV文件中讀取內容。如何在使用ngCordova文件插件中的readAsText時設置編碼

我只能在文件編碼爲unicode,但大多數CSV文件爲Shift-JIS時才能做到。我可以從文件中讀取什麼時候才Shift-JIS

我的代碼如下喜歡:

$cordovaFile.readAsText(cordova.file.documentsDirectory + CSVS_DIR, fileName).then(
    function (success) { 
     console.log("reading csv"); 
     console.log("csv content: " + success); 
    }, 
    function (error) { 
     console.log(error); 
     // error 
    }); 

是否有任何一個知道如何處理呢?

非常感謝。

回答

1

在這個問題上一整天后,我終於找到答案。

不幸的是,答案是否定的。我們無法通過使用readAsText來實現。

根據docs of ngCordova,API不支持cordova-file-plugin具有的readAsText函數中的編碼參數。

另外,讀完document of codova-file-plugin之後,我意識到Cordova-file-plugin中的readAsText函數在ios中運行時不支持編碼參數。

SOLUTION

由於readAsText不能做到這一點,我想在ngCordova提供的其他功能。我發現readAsBinaryString。這個函數似乎只是讀取文件的內容,不管它是什麼編碼。所以,我可以通過encoding.js閱讀內容並將其編碼爲Unicode。

代碼:

$cordovaFile.readAsBinaryString(cordova.file.documentsDirectory + CSVS_DIR, fileName).then(
    function (success) { 
     console.log("reading csv"); 
     console.log("csv content: " + success); 
     var detected = Encoding.detect(success); 
     success = Encoding.convert(success, { 
      to: 'UNICODE', // to_encoding 
      from: detected // from_encoding 
     }); 

     console.log("csv content: " + success);   
    }, 
    function (error) { 
     console.log(error); 
     // error  
    }); 

希望我的解決方案可以幫助。

相關問題