html頁面實現文件上傳

因爲業務的需求,需要實現一個通過瀏覽器把本地文件上傳到服務器的功能,因爲之前沒有做過,所以也是經過了一番探索才實現了這個功能,這裏只介紹前端的實現,後臺的接收、驗證和保存就不介紹了。

這個流程如下:

1、讀取本地文件

2、建立和服務器的連接(使用AJAX)

3、上傳一些頭信息和文件流

4、等待服務器響應後,顯示結果

 

讀取本地文件,在頁面中點擊 "瀏覽" 後,彈出文件選擇對話框,使用 <input type="file"/>標籤即可,如果要過濾指定後綴的文件,添加accept屬性,如只能選擇rar文件

<input class="style_file_content" accept=".rar" type="file" id="upload_file_id"/>

要通過js將文件讀取出來,需要用到 FileReader

var fReader = new FileReader();
fReader.onload=function(e){
   //讀取完成
   xhreq.send(fReader.result);
}
fReader.readAsArrayBuffer(uploadFile.files[0]);

讀取文件完成後,會回調onload 函數,文件內容保存在fReader.result,所以在onload 裏面把數據發生到服務器即可

和服務器建立連接,js代碼如下

function createHttpRequest()
 {
	 var xmlHttp=null;
     try{
 	    // Firefox, Opera 8.0+, Safari
 	    xmlHttp=new XMLHttpRequest();
 	 }catch (e){
 	    // Internet Explorer
 		try{
 	        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 	    }catch (e){
 		try{
 		    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 	        }catch (e){
 	            alert("您的瀏覽器不支持AJAX!");
 	        }
 	    }
 	}
    return xmlHttp;
 }

調用open 後纔會真正建立和服務器的連接,第一個參數是請求的方式,第二個參數是對應的URL 

xhreq.open("POST","/upload/file",true);
xhreq.setRequestHeader("Content-type", "application/octet-stream"); //流類型
xhreq.setRequestHeader("Content-length", fwFile.files[0].size);     //文件大小
xhreq.setRequestHeader("uploadfile_name", encodeURI(fwFile.files[0].name)); //兼容中文
xhreq.send(fReader.result);

因爲調用send()調用一次之後,就會把數據發送出去,比較難在內容裏面添加一些參數,比如文件名等信息,所以這裏鍵文件名放在header裏面,如 xhreq.setRequestHeader("uploadfile_name", encodeURI(fwFile.files[0].name)); //兼容中文。因爲如果header裏面的參數是中文的時候,後臺讀出來時會出現亂碼,所以需要encodeURI() 做一次編碼,後臺讀取後再做一次轉碼。

var xhreq=createHttpRequest();
xhreq.onreadystatechange=function(){
	if(xhreq.readyState==4){
		if(xhreq.status==200){
			uploadTip.innerText=xhreq.responseText;
			setTimeout(function(){
			hideUploadDialog()
			},2000);	//2秒後隱藏
		}else{
			uploadTip.innerText="文件上傳失敗了";
		}	
	 }
}

 在 請求發送給後臺的過程中,可以通過 onreadystatechange 這個會調函數知道當前的狀態,當 readyState 等於 4 且狀態爲 200 時,表示響應已就緒,響應的結果在xhreq.responseText。

 

完整的demo如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上傳測試</title>
</head>

<style type="text/css">
	#content_div{
   	position:absolute;
		left:0px;
		top:0px;
		right:0px;
		bottom:0px;
		text-align:center
  }
  
  .upload_dialog_div{
  position:fixed;
	left:0px;
	right:0px;
	top:0px;
	bottom:0px;
	overflow:auto; 
	visibility:hidden;
	background-color: rgba(60,60,60,0.5);
	z-index:99;
  }
  .style_content_div{
  position:relative;
  margin:auto;
  margin-top:160px;
	width:400px;
	height:160px;
	background:#F5F5DC;
  }
  .style_content_upper_div{
  position:absolute;
  left:0px;
  top:0px;
	width:400px;
	height:100px;
	background:#F5F5DC;
  }
  .style_content_lower_div{
  position:absolute;
  left:0px;
  top:100px;
	width:400px;
	height:60px;
	background:#F5FFDC;
  }
  
  .style_content_file_div{
  position:absolute;
  left:15px;
  top:20px;
	width:380px;
	height:60px;
  }
  .style_file_span{
	  float:left;
	  width:120px;
	  height:36px;
	  font-size:24px;
	  text-align:right;
  }
  .style_file_content{
	  margin-top:5px;
  }
  .style_content_prog_div{
  position:absolute;
  left:18px;
  top:57px;
	width:360px;
	height:40px;
  }
  .style_prog_span_hit{
	  color:#ff0000;
  }
  .style_prog_content{
	  width:360px;
	  visibility:hidden;
  }
  .style_content_span{
  width:200px;
	height:60px;
	line-height:60px;
	display:inline-block;
	float:left;
	font-size:32px;
	text-align:center;
	cursor: pointer;
  }

  .style_copyright_a{
	text-decoration:none;
	color:#cc00cc;
  }
</style>
<script>
function createHttpRequest()
 {
	 var xmlHttp=null;
     try{
 	    // Firefox, Opera 8.0+, Safari
 	    xmlHttp=new XMLHttpRequest();
 	 }catch (e){
 	    // Internet Explorer
 		try{
 	        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 	    }catch (e){
 		try{
 		    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 	        }catch (e){
 	            alert("您的瀏覽器不支持AJAX!");
 	        }
 	    }
 	}
    return xmlHttp;
 }
 
 function uploadFileToServer(){
	var uploadFile = document.getElementById("upload_file_id");
	var uploadTip = document.getElementById("upload_tip_id");
	var uploadProgress = document.getElementById("upload_progress_id");
	
	if(uploadFile.value==""){
		 uploadTip.innerText="請選擇一個文件";
	}else if(uploadFile.files[0].size>1024 &&uploadFile.files[0].size<(40*1024*1024)){ 
		try{
			if(window.FileReader){
				var fReader = new FileReader();
				var xhreq=createHttpRequest();
				 xhreq.onreadystatechange=function(){
					 if(xhreq.readyState==4){
						if(xhreq.status==200){
							 uploadTip.innerText="文件上傳成功";
							 setTimeout(function(){
								hideUploadDialog()
							},2000);	//2秒後隱藏
						}else{
							uploadTip.innerText="文件上傳失敗了";
						}	
					 }
				 }
				fReader.onload=function(e){
					 xhreq.open("POST","/upload/file",true);
					 xhreq.setRequestHeader("Content-type", "application/octet-stream"); //流類型
					 xhreq.setRequestHeader("Content-length", fwFile.files[0].size);     //文件大小
					 xhreq.setRequestHeader("uploadfile_name", encodeURI(fwFile.files[0].name)); //兼容中文
					 xhreq.send(fReader.result);
				}
				fReader.onprogress = function(e){
					 uploadProgress.value = e.loaded*100/e.total;
				}
				fReader.readAsArrayBuffer(uploadFile.files[0]);
				uploadProgress.style.visibility="visible";
				uploadProgress.value = 0;
			}else{
				uploadTip.innerText="瀏覽器不支持上傳文件";
			}			
		}catch(e){
			 uploadTip.innerText="文件上傳失敗";
		}
	}else{
		  uploadTip.innerText="文件不符合要求";
	}
}
 function showUploadDialog(){
	var up_dialog=document.getElementById("upload_dialog");
  document.getElementById("upload_tip_id").innerText="請選擇要上傳的文件";
  document.getElementById("upload_progress_id").style.visibility="hidden";
	up_dialog.style.visibility="visible";
	
 }
 function hideUploadDialog(){
	var up_dialog=document.getElementById("upload_dialog");
	document.getElementById("upload_progress_id").style.visibility="hidden";
	up_dialog.style.visibility="hidden";
 }
</script>
<body>
   <div id="content_div">
   	  <br>
   	  <br>
   	  <br>
   	  <br>
   	  <br>
   	  <a class="style_copyright_a" href="javascript:void(0);" onclick="showUploadDialog()">上傳新文件</a>
   </div>
   
   <div id="upload_dialog" class="upload_dialog_div"> 
   	    <div class="style_content_div">
  	  	  <div class="style_content_upper_div">
  	  	  	  <div class="style_content_file_div">
  	  	  	  	 <span class="style_file_span"> 文件路徑:</span>
  	  	  	  	 <input class="style_file_content" type="file" id="upload_file_id"/>
  	  	  	  </div>
  	  	  	  <div class="style_content_prog_div">
  	  	  	  	 <span class="style_prog_span_hit" id="upload_tip_id"> 請選擇要上傳的文件 </span>
  	  	  	     <progress class="style_prog_content" id="upload_progress_id" value="0" max="100"></progress> 
  	  	  	  </div>
  	  	  </div>
  	  	  <div class="style_content_lower_div">
  	  	  	   <span class="style_content_span" onmouseover="this.style.background='#cccccc'" onmouseout="this.style.background=''" onclick="hideUploadDialog()">取消</span>
  	  	  	   <span class="style_content_span" onmouseover="this.style.background='#F5CCDC'" onmouseout="this.style.background=''" onclick="uploadFileToServer()">確定</span>
  	  	  </div>
  	  </div>
   </div>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章