1 <head> 2 <title>图片上传</title> 3 <script src="../Scripts/jquery-1.7.1.js"></script> 4 <script type="text/javascript"> 5 $(function () { 6 $(":file").change(function(){ 7 // alert("change"); 8 9 //拿到文件名 10 // alert($(this).val()); 11 12 //获取后缀 13 var fileName = $(this).val(); 14 var ext = fileName.substr(fileName.lastIndexOf(‘.‘)); 15 if (ext ==".jpg" || ext==".jpeg" || ext==".png" || ext ==".gif") { 16 return true 17 } else { 18 //清空选中文件 19 $(this).val(""); 20 alert("请选择正确文件"); 21 } 22 }); 23 24 }); 25 26 </script> 27 28 </head> 29 <body> 30 <form action="ImageUpload.ashx" method="post" enctype="multipart/form-data"> 31 32 <input type="file" name="imgFile" /> 33 <input type="submit" name="name" value="上传 " /> 34 35 </form> 36 <!--<form action="ImageUpload.ashx" method="post"> 37 <input type="text" name="txtName" value=" " /> 38 <input type="submit" name="name" value="提交 " /> 39 40 </form>--> 41 </body>
1 context.Response.ContentType = "text/html"; 2 3 //拿到上传的文件 4 HttpPostedFile file = context.Request.Files["imgFile"]; 5 6 //后台也要校验 7 string ext = file.FileName.Substring(file.FileName.LastIndexOf(".")); 8 9 if (!(ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif")) 10 { 11 //不是图片的时候 12 context.Response.Write("shit"); 13 context.Response.End(); 14 15 16 } 17 else 18 { 19 string path = "/Upload/" + Guid.NewGuid() + file.FileName; 20 21 file.SaveAs(context.Request.MapPath(path)); 22 23 string str = string.Format("<html><head></head><body><img src=‘{0}‘/></body></html>", path); 24 25 context.Response.Write(str); 26 }
原文:http://www.cnblogs.com/allenzhang/p/6732747.html