天天看點

使用input讀取檔案

讀取一個包含文本内容的檔案,代碼如下:

<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#fileOutput{
			width: 400px;
			height: 300px;
			border:1px solid red;
		}
	</style>
</head>
<body>
	<input type="file" id="fileInput" οnchange="processFiles(this.files)">
	<div id="fileOutput"></div>
	<script type="text/javascript">
		function processFiles(files){
			// 得到第一個檔案
			var file = files[0];
			//建立一個FileReader對象
			var reader = new FileReader();
			reader.οnlοad=function(e){
				var output = document.getElementById("fileOutput");
				output.textContent = e.target.result;
			}
			reader.readAsText(file);
			// readAsText隻能夠處理包含文本内容的檔案csv,xml,html等,不能夠處理二進制檔案
		}
	</script>
</body>
</html>
           

讀取一個檔案不過瘾,那麼我們讀取多個檔案試試,其實我們隻要在選擇檔案加一個multiple。然後對于顯示内容做一個循環處理就可以了,代碼如下:

<!DOCTYPE html>
<html >
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#fileOutput{
			width: 400px;
			height: 300px;
			border:1px solid red;
		}
	</style>
</head>
<body>
	<input type="file" id="fileInput" οnchange="processFiles(this.files)" multiple>
	<div id="fileOutput"></div>
	<script type="text/javascript">
		function showFileInput(){
			var fileInput = document.getElementById("fileInput");
			fileInput.click();
		}
		function processFiles(files){
				for(var i=0;i<files.length;i++){
					// 得到第一個檔案
					var file = files[i];
					//建立一個FileReader對象
					var reader = new FileReader();
					reader.οnlοad=function(e){
						var output = document.getElementById("fileOutput");
						output.textContent += e.target.result;
					}
					reader.readAsText(file);
				}
		}
	</script>
</body>
</html>
           

繼續閱讀