介绍三种上传方式:
伪刷新,在iframe标签进行上传提交操作,因为iframe已经隐藏了,它刷新了用户也看不到
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 <script> 7 onload = function () { 8 filedata.onchange = function () { 9 if (filedata.files.length > 0) { 10 form1.submit(); 11 } 12 }; 13 btn1.onclick = function () { 14 var str = iframeBox.document.body.innerHTML; 15 var res = JSON.parse(str); 16 p1.innerHTML = str; 17 if (res.Path) { 18 p2.innerHTML = '<img src="' + res.Path + '" />'; 19 } 20 }; 21 }; 22 </script> 23 </head> 24 <body> 25 26 <form id="form1" method="post" enctype="multipart/form-data" target="iframeBox" action="Handler1.ashx"> 27 <input type="file" id="filedata" name="FileData" /> 28 </form> 29 30 <iframe id="iframeBox" name="iframeBox" style="display:none"></iframe> 31 32 <br /> 33 34 <div> 35 <input type="button" id="btn1" value="获取返回值" /> 36 <p id="p1"></p> 37 <p id="p2"></p> 38 </div> 39 40 </body> 41 </html>
Handler1.ashx的处理:
1 public void ProcessRequest(HttpContext context) 2 { 3 HttpPostedFile file = context.Request.Files["FileData"]; 4 if (!file.ContentType.Contains("image/")) 5 { 6 context.Response.Write("{"Msg":"请上传图片!","Path":""}"); 7 context.Response.End(); 8 } 9 string[] arr = file.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); 10 11 DateTime now = DateTime.Now; 12 string fileName = Guid.NewGuid().ToString() + "." + arr[arr.Length - 1]; 13 string relPath = string.Format("/Upload/{0}{1}{2}/", now.Year.ToString(), now.Month.ToString(), now.Day.ToString()); 14 string absPath = context.Request.MapPath("~" + relPath); 15 if (!Directory.Exists(absPath)) 16 { 17 Directory.CreateDirectory(absPath); 18 } 19 file.SaveAs(absPath + fileName); 20 21 context.Response.Write("{"Msg":"成功!","Path":"" + relPath + fileName + ""}"); 22 }