工作上的需要,需要用到很多个文件里的代码,一个个打开复制又过去沙雕,就看看用js怎么解决了(其实用python应该更加方便,奈何本人python只会一点皮毛)
引用:借鉴的博客
话不多说,直接上代码
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<!-- Code Here -->
<input type="file" name="upload" id="upload" accept="text/plain"/>
<p name="content" id="content"></p>
<script>
window.onload = function() {
/**
* 上传函数
* @param fileInput DOM对象
* @param callback 回调函数
*/
var getFileContent = function (fileInput, callback) {
if (fileInput.files && fileInput.files.length > 0 && fileInput.files[0].size > 0) {
//下面这一句相当于JQuery的:var file =$("#upload").prop('files')[0];
var file = fileInput.files[0];
if (window.FileReader) {
var reader = new FileReader();
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
callback(evt.target.result);
}
};
// 包含中文内容用gbk编码
reader.readAsText(file, 'utf-8');
}
}
};
/**
* upload内容变化时载入内容
*/
document.getElementById('upload').onchange = function () {
console.log("hahahah ")
var content = document.getElementById('content');
getFileContent(this, function (str) {
console.log(str);
str=str.replace(/\n/g,"<br/>"); //格式保留,追加换行
content.innerHTML += str;
});
};
};
</script>
</body>
</html>
str=str.replace(/\n/g,"<br/>");
一开始没有上面这一句代码的时候,输出是没有换行的,格式混乱,后来在网上找到了这个方法,匹配"\n",就可以替换成换行标签了,当然,有可能文件里的换行符并不是''\n",那么试试"\r", "\r\n",总会有一个是的。
reader.readAsText(file, 'utf-8');
另外要注意的是要用"utf-8"编码读取文件
下面是效果图
