Because of the needs of the business , Need to achieve a browser to upload local files to the server function , Because I haven't done it before , So it is also after some exploration to achieve this function , Here is just the implementation of the front end , Background reception , Verification and preservation will not be introduced .
The process is as follows :
1, Read local file
2, Establish a connection to the server ( use AJAX)
3, Upload some header information and file stream
4, Wait for the server to respond , Show results
Read local file , Click in the page " browse " after , Pop up the file selection dialog box , use <input
type="file"/> Just label , If you want to filter the file with the specified suffix , add to accept attribute , If you can only choose rar file
<input class="style_file_content" accept=".rar" type="file"
id="upload_file_id"/>
To pass js Read the file out , Need to use FileReader
var fReader = new FileReader(); fReader.onload=function(e){ // Read complete
xhreq.send(fReader.result); } fReader.readAsArrayBuffer(uploadFile.files[0]);
After reading the file , Will call back onload function , The contents of the file are saved in fReader.result, So in onload It can generate data to the server
Establish a connection with the server ,js The code is as follows
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(" Your browser does not support AJAX!"); } } }
return xmlHttp; }
call open After that, the connection with the server will be established , The first parameter is how the request is made , The second parameter corresponds URL
xhreq.open("POST","/upload/file",true); xhreq.setRequestHeader("Content-type",
"application/octet-stream"); // Stream type xhreq.setRequestHeader("Content-length",
fwFile.files[0].size); // file size xhreq.setRequestHeader("uploadfile_name",
encodeURI(fwFile.files[0].name)); // Chinese compatible xhreq.send(fReader.result);
Because of the call send() After one call , It will send out the data , It is difficult to add some parameters to the content , For example, file name and other information , So here you put the key file name in the header inside , as xhreq.setRequestHeader("uploadfile_name",
encodeURI(fwFile.files[0].name));
// Chinese compatible . Because if header When the parameters are in Chinese , Background read out when there will be garbled , So we need to encodeURI() Do a coding , Do transcoding again after background reading .
var xhreq=createHttpRequest(); xhreq.onreadystatechange=function(){
if(xhreq.readyState==4){ if(xhreq.status==200){
uploadTip.innerText=xhreq.responseText; setTimeout(function(){
hideUploadDialog() },2000); //2 Hide in seconds }else{ uploadTip.innerText=" File upload failed "; } } }
stay In the process of sending the request to the background , Can pass onreadystatechange This call function knows the current state , When readyState be equal to 4 And the state is
200 Time , Indicates that the response is ready , The results of the response are xhreq.responseText.
complete demo as follows :
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> File upload test </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(" Your browser does not support 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=" Please select a file "; }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=" File uploaded successfully "; setTimeout(function(){
hideUploadDialog() },2000); //2 Hide in seconds }else{ uploadTip.innerText=" File upload failed "; } } }
fReader.onload=function(e){ xhreq.open("POST","/upload/file",true);
xhreq.setRequestHeader("Content-type", "application/octet-stream"); // Stream type
xhreq.setRequestHeader("Content-length", fwFile.files[0].size); // file size
xhreq.setRequestHeader("uploadfile_name", encodeURI(fwFile.files[0].name));
// Chinese compatible 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=" The browser does not support uploading files "; } }catch(e){ uploadTip.innerText=" File upload failed "; }
}else{ uploadTip.innerText=" The document does not meet the requirements "; } } function showUploadDialog(){ var
up_dialog=document.getElementById("upload_dialog");
document.getElementById("upload_tip_id").innerText=" Please select the file to upload ";
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()"> Upload new file </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"> File path :</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"> Please select the file to upload </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()"> cancel </span>
<span class="style_content_span" onmouseover="this.style.background='#F5CCDC'"
onmouseout="this.style.background=''" onclick="uploadFileToServer()"> determine </span>
</div> </div> </div> </body> </html>
Technology