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

查看:66
本文介绍了使用 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.

我有一个 input:file 表单.更改时我正在阅读内容

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(/
/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"(至少由 Google 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 答案,您应该设法构建一个函数,将 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天全站免登陆