我尝试使用从 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/