2017-10-10 24 views
0

我想解析一個csv文件,但是這個文件格式是ANSI的。所以,當我打印出網頁上的結果,它看起來像如下: ANSI file outputjs如何將字符串轉換爲utf-8

我用下面的代碼在我的測試php文件將字符串轉換:

iconv(mb_detect_encoding($str, mb_detect_order(), true), "UTF-8", $str); 

那麼它現在看起來正常的,因爲這:

normal output

但我想要做的上前方側的轉換,使用JS,所以有任何方法將字符串轉換爲UTF-8格式如php方法 - >的iconv()。

謝謝。

+0

如果你可以使用節點,看在覈心模塊, 'string_decoder'。 – YvesLeBorg

+0

ANSI使用什麼代碼頁,完全是?沒有像「ANSI」那樣的東西。 – RocketNuts

回答

1

下面是使用文件輸入控制讀取一個文件中的示例代碼和一些文件的屬性沿顯示第一行:

<input type="file" id="fileinput" /> 
<script type="text/javascript"> 
function readSingleFile(evt) { 
//Retrieve the first (and only!) File from the FileList object 
var f = evt.target.files[0]; 

if (f) { 
    var r = new FileReader(); 
    r.onload = function(e) { 
     var contents = e.target.result; 
    alert("Got the file.n" 
      +"name: " + f.name + "n" 
      +"type: " + f.type + "n" 
      +"size: " + f.size + " bytesn" 
      + "starts with: " + contents.substr(1, contents.indexOf("n")) 
    ); 
    } 
    r.readAsText(f); 
    } else { 
    alert("Failed to load file"); 
    } 
} 

document.getElementById('fileinput').addEventListener('change', readSingleFile, false); 
</script> 

您可以使用閱讀文件使用HTML5的FileReader API。嘗試加載錯誤的編碼時內容被破壞後嘗試轉換文件是沒有意義的。

,如果你想要去的內心深處試着看下面的文章:

htmlgoodies

html5rocks

+0

謝謝,但問題是原始文件格式是在ANSI中,所以我想使文件格式爲UTF-8,或將讀取的字符串轉換爲utf-8。 –