前台JS(type=‘file’)读取本地文件的内容,兼容各种浏览器 二

前台js读取本地文件内容方法:

1、IE用new ActiveXObject("Scripting.FileSystemObject")

2、其它用FileReader对象 html5的方法

说法不严谨。详细自己測试,复制下面代码保存为html直接能够执行。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
//IE 10 下面中问可能会乱码 不能读utf-8格式的文本
function upload(input) {
	if (typeof window.ActiveXObject != 'undefined') {
		var file = input.value;
		var content = "";
		try {
			var fso = new ActiveXObject("Scripting.FileSystemObject");
			var reader = fso.openTextFile(file, 1);
			/*while (!reader.AtEndofStream) {
				content += reader.readline();
				content += "
";
			}*/
			content = reader.readAll();
			reader.close();
		} catch (e) {
			alert("Internet Explore read local file error: 
" + e);
		}
		
		console.log(content);
		alert(content);
	} else {
		var file = input.files[0];
		filename = file.name.split(".")[0];
		var reader = new FileReader();
		reader.onload = function() {
			console.log(this.result)
			alert(this.result);
		}
		reader.readAsText(file);
	}
}
</script>
<title>file upload</title>
</head>
<body>
	<input type="file" onchange="upload(this)" />
</body>
</html>

希望对你实用。

原文地址:https://www.cnblogs.com/lcchuguo/p/5168111.html