Because of business requirements, need to achieve a browser to upload local files to the server function, because it has not been done before, so it is also through some exploration to achieve this function, here only introduces the front-end implementation, background reception, verification and preservation will not be introduced.

The process is as follows:

1. Read local files

2. Establish a connection to the server (using AJAX)

Upload some headers and file streams

4. Wait for the server to respond and display the result

 

After reading local files, click “Browse” on the page, and the dialog box for selecting files pops up. Use the label. If you want to filter files with the specified suffix, add the Accept attribute, for example, only rar files can be selected

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

To read the file from JS, you need FileReader

var fReader = new FileReader(); Freader. onload=function(e){freader. result (freader.result); } fReader.readAsArrayBuffer(uploadFile.files[0]);Copy the code

When the file is loaded, the onload function is called, and the file contents are stored in freader.result

To establish a connection with the server, the js 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; }Copy the code

The connection to the server is actually established after the call to open. The first parameter is the request method and the second parameter is the corresponding URL

xhreq.open("POST","/upload/file",true); xhreq.setRequestHeader("Content-type", "application/octet-stream"); // Stream type xhreq.setrequesTheader (" Content-Length ", fwfile.files [0].size); Xhreq.setrequestheader (" uploadFile_name ", encodeURI(fwfile.files [0].name)); Xhreq. send(freader.result);Copy the code

Because send() sends the data once, it’s hard to add parameters like the file name, so put the key file name inside the header. Such as xhreq. SetRequestHeader (” uploadfile_name, “encodeURI (fwFile. Files [0]. Name)); // Compatible with Chinese. If the parameters in the header are In Chinese, garbled characters will appear in background reading, so encodeURI() is required for encoding, and then transcoding 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); }else{uploadTip. InnerText =" File upload failed "; }}}Copy the code

The onReadyStatechange callback function lets you know the current status of the request while it is being sent to the background. When readyState is 4 and the status is 200, the response is ready and the result of the response is xhreq.responseText.

The full demo is as follows:

<! < HTML > <head> <meta charset=" utF-8 "> </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. setTimeout(function(){ hideUploadDialog() },2000); }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); 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 =" Browser does not support uploading files "; }}catch(e){uploadtip.innertext =" Uploadtip.innertext "; }}else{uploadTip. InnerText =" error "; } } 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);" 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=''" <span > <span class=" style_content_SPAN "onmouseover="this.style.background='#F5CCDC'" onclick="hideUploadDialog()"> Onmouseout ="this.style.background= "" onclick="uploadFileToServer()" </span> </div> </div> </body> </ HTML >Copy the code

If you think it’s good, please like, bookmark and forward ❤❤❤~

You can get PDF book source code, tutorials, etc., for everyone to use free click the link to join [Web front-end technology] :jq.qq.com/?_wv=1027&k…