使用javascript的FileReader获取/设置文件编码 [英] Get/set file encoding with javascript's FileReader

查看:130
本文介绍了使用javascript的FileReader获取/设置文件编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决以下问题。使用javascript我想更改文件内容的字符集并将此内容显示给用户。

I am struggling with the following problem. Using javascript I would like to change the character set of a file content and display this content to the user.

我有一个输入:文件格式。在改变时我正在阅读内容

I have an input:file form. On change I am reading the content

$('#form input:file').change(function(event){                   
   file = this.files[0];
   reader = new FileReader();
   reader.onload = function(event) {
      result = event.target.result.replace(/\n/g,'<br />');
      $('#filecontents').html(result);
   });
   reader.readAsText(file);
})

该文件位于Windows-1251中。我想将文件的内容转换为另一种编码,之后将其呈现给用户。

The file is in Windows-1251. I would like to convert the content of the file to another encoding and after that present it to the user.

这可以用javascript实现吗?

Is this possible to achieve with javascript?

问候

推荐答案

如果你的HTML页面是UTF-8而你的文件是ISO-8859-1。

If your HTML page is in UTF-8 and your file is in ISO-8859-1.

这是有效的:

 reader.readAsText(file, 'ISO-8859-1');

我没有任何Windows-1251文件,所以我无法测试它,但它看起来就像支持'CP1251'(至少谷歌Chrome),所以:

I don't have any Windows-1251 file so I was not able to test it but it looks like that the 'CP1251' is supported (by Google Chrome at least), so:

 reader.readAsText(file, 'CP1251');






如果这些都不起作用。然后你应该手动更改格式。不幸的是,我不知道任何JavaScript库可以解决问题。


If none of this is working. Then you should change the formatting manually. Unfortunately, I am not aware of any JavaScript library that does the trick.

来自unicode映射此处 Delan Azabani 回答,您应该设法构建一个函数,将char中的字符串转换为CP1251中的字符串为UTF-8 。

From the unicode mapping here and from Delan Azabani answer, you should manage to build a function that convert char by char your string in CP1251 to UTF-8.

这篇关于使用javascript的FileReader获取/设置文件编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆