本人菜鸟,第一次写博客,不会排版,只是记录工作中常用的东西
ajaxfileupload.js源码:
http://www.rczjp.cn/HTML/110420/20113620053635.html
前台:
<script src="../res/js/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script> <script type="text/javascript"> function ajaxFileUpload() { $.ajaxFileUpload( { url: 'Handler.ashx', //需要链接到服务器地址 secureuri: false, fileElementId: 'FileUpload', //文件选择框的id属性 dataType: 'json', //服务器返回的格式,可以是json success: function (data, status) //相当于java中try语句块的用法 { $("#pic_1").attr("src", "../uploadfiles/" + data.msg + ""); }, error: function (data, status, e) //相当于java中catch语句块的用法 { alert(data.error); } } ); } </script> <body> <table class="pro_pic_tb"> <tbody> <tr> <td> <div class="picdiv3"> <img src="http://www.rhebank.com/admin/images/nopic.jpg" id="pic_1" height="100" width="100"> <div class="picdel" id="picdel_1"> <img src="http://www.rhebank.com/admin/images/del.gif" onclick="delPic(1,'resume')"></div> </div> <p> <span class="input-file">上传图片 <asp:FileUpload runat="server" ID="FileUpload" onchange="javascript:ajaxFileUpload();"/> </span> <input name="photo" class="hidden" id="photo" > </p> </td> </tr> </tbody> </table> </body>
下面是后台程序源码:
1 <%@ WebHandler Language="C#" Class="Handler" %> 2 3 using System; 4 using System.Web; 5 6 public class Handler : IHttpHandler { 7 8 public void ProcessRequest (HttpContext context) { 9 context.Response.ContentType = "text/plain"; 10 11 if (context.Request.Files.Count > 0) 12 { 13 string path = context.Server.MapPath("~/uploadfiles/"); 14 15 var file = context.Request.Files[0]; 16 17 string fileName; 18 19 if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") 20 { 21 string[] files = file.FileName.Split(new char[] { '\\' }); 22 fileName = files[files.Length - 1]; 23 } 24 else 25 { 26 fileName = file.FileName; 27 } 28 29 30 31 string msg = ""; 32 string strFileName = fileName; 33 if (string.IsNullOrEmpty(strFileName)) 34 { 35 msg = "{"; 36 msg += string.Format("error:'{0}',\n", "请选择文件!"); 37 msg += string.Format("msg:'{0}'\n", string.Empty); 38 msg += "}"; 39 } 40 else 41 { 42 fileName = System.IO.Path.Combine(path, fileName); 43 file.SaveAs(fileName); 44 45 msg = "{"; 46 msg += string.Format("error:'{0}',\n", string.Empty); 47 msg += string.Format("msg:'{0}'\n", strFileName); 48 msg += "}"; 49 } 50 context.Response.Write(msg); 51 52 53 } 54 } 55 56 public bool IsReusable { 57 get { 58 return false; 59 } 60 } 61 62 }
没什么特殊的,只是做个标记