javascript - HTML5 文件 api,读取 xml/文本文件并将其显示在页面上?

标签 javascript file html

我尝试使用从 http://www.html5rocks.com/tutorials/file/dndfiles/ 修改的以下代码读取文本或 xml 文件并显示下面的内容。

<!DOCTYPE html> 
<html> 
<head> 
    <title>reading xml</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head>
<body>
    <input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>

    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // Loop through the FileList
        for (var i = 0, f; f = files[i]; i++) {

          var reader = new FileReader();

          // Closure to capture the file information.
          reader.onload = (function(theFile) {
            return function(e) {
              // Print the contents of the file
              var span = document.createElement('span');                    
              span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
              document.getElementById('list').insertBefore(span, null);
            };
          })(f);

          // Read in the file
          //reader.readAsDataText(f,UTF-8);
          reader.readAsDataURL(f);
        }
      }

      document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>
</body>

reader.readAsDataText(f,UTF-8);不工作

reader.readAsDataURL(f);以 Base64 显示文件

如何让文本文件显示在页面上?

最佳答案

需要将编码作为字符串传入;在 UTF-8 两边加上引号。此外,它是 readAsText,而不是 readAsDataText:

reader.readAsText(f,"UTF-8");

或者您可以完全关闭编码,在这种情况下,它会尝试自动检测 UTF-16BE 或 LE,如果不是其中之一,它会默认使用 UTF-8。

reader.readAsText(f);

关于javascript - HTML5 文件 api,读取 xml/文本文件并将其显示在页面上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5744064/

相关文章:

c - Unix 中中断时 Read() 的行为

javascript - 从 html 'value' 属性中检索值

html - tr 单元格宽度根据父表头宽度

javascript - 根据视口(viewport)高度为 x 图像行分配相同的高度

javascript - 我如何将 gulp 与磁带一起使用?

javascript - 使用 DTrace 分析 Node.js

javascript - 是否有类似 SailsJS 的 MEAN 堆栈的样板文件?

java - 直接使用java修改XML文件

C++从文件阅读器中的另一个类调用set函数

php - 如何使用 php DomDocument 获取特定标签的 html