html5檔案上傳

niunan發表於2016-03-23
htmL程式碼:
  1.        <div class=“row”>   
  2.       <input type=“file” name=“fileToUpload” id=“fileToUpload” onchange=“fileSelected();”/>  
  3.     </div>   
  4.     <div id=“fileSize”></div>  
  5.     <div id=“fileType”></div>  
  6.     <div class=“row”>  
  7.       <input type=“button” onclick=“uploadFile()” value=“上傳” />  
  8.     </div>  
  9.     <div id=“progressNumber”></div>  
  10.                 <progress max=“100” id=“progre” value=“0”></progress>  
  11.                 <br />  
  12.                 <asp:Image ID=“Image1”  Style=“max-width:130px” runat=“server” />  
  13.                 <asp:HiddenField ID=“hfimg” value=“” runat=“server” />  

JS程式碼:

  1.       <script type=“text/javascript”>  
  2.         function fileSelected() {  
  3.             var file = document.getElementById(`fileToUpload`).files[0];  
  4.             if (file) {  
  5.                 var fileSize = 0;  
  6.                 if (file.size > 1024 * 1024)  
  7.                     fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + `MB`;  
  8.                 else  
  9.                     fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + `KB`;  
  10.   
  11.             
  12.                 document.getElementById(`fileSize`).innerHTML = `檔案大小: ` + fileSize;  
  13.                 document.getElementById(`fileType`).innerHTML = `檔案型別: ` + file.type;  
  14.             }  
  15.         }  
  16.   
  17.         function uploadFile() {  
  18.             var fd = new FormData();  
  19.             fd.append(“fileToUpload”, document.getElementById(`fileToUpload`).files[0]);  
  20.             var xhr = new XMLHttpRequest();  
  21.             xhr.upload.addEventListener(“progress”, uploadProgress, false);  
  22.             xhr.addEventListener(“load”, uploadComplete, false);  
  23.             xhr.addEventListener(“error”, uploadFailed, false);  
  24.             xhr.addEventListener(“abort”, uploadCanceled, false);  
  25.             xhr.open(“POST”, “/handler/h5upload.ashx”);  
  26.             xhr.send(fd);  
  27.         }  
  28.   
  29.         function uploadProgress(evt) {  
  30.             if (evt.lengthComputable) {  
  31.                 var percentComplete = Math.round(evt.loaded * 100 / evt.total);  
  32.                 document.getElementById(`progressNumber`).innerHTML = percentComplete.toString() + `%`;  
  33.                 document.getElementById(`progre`).value = percentComplete;  
  34.             }  
  35.             else {  
  36.                 document.getElementById(`progressNumber`).innerHTML = `unable to compute`;  
  37.             }  
  38.         }  
  39.   
  40.         function uploadComplete(evt) {  
  41.             /* This event is raised when the server send back a response */   
  42.           var json =eval(“(“+ evt.target.responseText+“)”);  
  43.           if (json.status==“no”) {  
  44.               alert(json.info);  
  45.           }else{  
  46.             document.getElementById(“<%=Image1.ClientID%>”).src = json.path;  
  47.             document.getElementById(“<%=hfimg.ClientID%>”).value = json.path;   
  48.           }  
  49.         }  
  50.   
  51.         function uploadFailed(evt) {  
  52.             alert(“There was an error attempting to upload the file.”);  
  53.         }  
  54.   
  55.         function uploadCanceled(evt) {  
  56.             alert(“The upload has been canceled by the user or the browser dropped the connection.”);  
  57.         }  
  58.     </script>  

後臺ashx程式碼:

  1.     context.Response.ContentType = “text/plain”;  
  2.             HttpPostedFile  file =context. Request.Files[“fileToUpload”];  
  3.             String fileName = file.FileName;  
  4.             String fileExt = Path.GetExtension(fileName).ToLower();  
  5.   
  6.             //定義允許上傳的副檔名  
  7.             Hashtable extTable = new Hashtable();  
  8.             extTable.Add(“image”, “gif,jpg,jpeg,png,bmp”);  
  9.             extTable.Add(“flash”, “swf,flv”);  
  10.             extTable.Add(“media”, “swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb”);  
  11.             extTable.Add(“file”, “doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2”);  
  12.   
  13.             if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[“image”]).Split(`,`), fileExt.Substring(1).ToLower()) == -1)  
  14.             {  
  15.                 context.Response.Write(LitJson.JsonMapper.ToJson(new { status=“no”, info = “上傳副檔名是不允許的副檔名。  
  16. 只允許” + ((String)extTable[“image“]) + “格式。” }));  
  17.                        
  18.                 return;  
  19.             }  
  20.             string dirpath = “/upload/”+DateTime.Now.ToString(“yyyyMMdd”)+“/”;  
  21.             if (!Directory.Exists(context.Server.MapPath( dirpath)))  
  22.             {  
  23.                 Directory.CreateDirectory(context.Server.MapPath(dirpath));  
  24.             }  
  25.             String newFileName = DateTime.Now.ToString(“yyyyMMddHHmmss_ffff”, DateTimeFormatInfo.InvariantInfo) + fileExt;  
  26.   
  27.             file.SaveAs(context.Server.MapPath(dirpath) + newFileName);  
  28.             context.Response.Write(LitJson.JsonMapper.ToJson(new { status=“ok”,path = dirpath+newFileName}));  

瀏覽(505) | 評論(0) | 分類: javascript


相關文章