Syc*_*ren 6 html javascript html5 file
我尝试使用从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>
Run Code Online (Sandbox Code Playgroud)
reader.readAsDataText(F,UTF-8); 不行
reader.readAsDataURL(F); 在Base64中显示该文件
如何获取要在页面上显示的文本文件?
Bri*_*ell 12
您需要将编码作为字符串传递; 把报价放在周围UTF-8.而且,它readAsText不是readAsDataText:
reader.readAsText(f,"UTF-8");
Run Code Online (Sandbox Code Playgroud)
或者你可以完全关闭编码,在这种情况下它将尝试自动检测UTF-16BE或LE,如果它不是其中之一,它将默认使用UTF-8.
reader.readAsText(f);
Run Code Online (Sandbox Code Playgroud)