前台代码:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <style type="text/css"> #div1{300px;height:30px;border:1px solid #000;position:relative;} #div2{0px;height:30px;background:#CCC;} #div3 { 300px; height: 30px; line-height: 30px; text-align: center; position: absolute; left:0px;top:0px; } </style> </head> <body> <input type="file" id="file"/><input type="button" id="btnFile" value="上传" /> <!--进度条--> <div id="div1"> <div id="div2"></div> <div id="div3">0%</div> </div> </body> </html> <script type="text/javascript"> var file = document.getElementById("file"); var btnFile = document.getElementById("btnFile"); var div1 = document.getElementById("div1"); var div2 = document.getElementById("div2"); var div3 = document.getElementById("div3"); btnFile.onclick = function () { var xml = new XMLHttpRequest(); xml.onload = function () { alert(xml.responseText); } //上传进度条事件 var oUpload = xml.upload; oUpload.onprogress = function (ev) { //console.log(ev.total + ":" + ev.loaded);//ev.loaded是已经上传的 ev.total是总的 var iScale = ev.loaded / ev.total;//计算出比例 div2.style.width = 300 * iScale + "px"; div3.innerHTML = iScale*100 + "%"; } xml.open("post", "HandlerFiles.ashx", true); xml.setRequestHeader('X-Request-Width', 'XMLHttpRequest'); var oFormData = new FormData(); oFormData.append("file",file.files[0]); xml.send(oFormData); } </script>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Ajax无刷新上传 { /// <summary> /// HandlerFiles 的摘要说明 /// </summary> public class HandlerFiles : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; int rec = context.Request.Files.Count; if (context.Request.Files.Count > 0) { HttpPostedFile files = context.Request.Files[0]; if (files.ContentLength > 0) { int n=files.ContentLength; string fileName = files.FileName; files.SaveAs(context.Request.MapPath("files/"+Guid.NewGuid().ToString()+"_"+fileName)); context.Response.Write("上传完毕!"); context.Response.End(); } else { context.Response.Write("选择的文件不能小于0字节"); context.Response.End(); } } else { context.Response.Write("请先选择上传文件"); context.Response.End(); } } public bool IsReusable { get { return false; } } } }
GitHub项目链接:https://github.com/shuai7boy/AjaxUploadFiles