Jquery ajaxsubmit 异步上传图片 无刷新

先前有做异步上传,但是好像都没成功,看到网友的一篇博客,先记录下来,以后看能不能用到

异步上传图片的步骤如下:

      1.引用 jquery js 框架(这东西的好处无需多论)后再引用 “jquery.form.js”。

      2.建立一般处理程序 ashx。

    核心代码如下:

     html:

   
   
   
   
1 < asp:Content ID = " Content3 " ContentPlaceHolderID = " Head " runat = " server " >
2 < script src = " <%=Url.Content( " ~/ Scripts / jquery - 1.4 . 1 .js " ) %> " type = " text/javascript " ></ script >
3 < script src = " <%=Url.Content( " ~/ Scripts / jquery.form.js " ) %> " type = " text/javascript " ></ script >
4 < script type = " text/javascript " >
5 $(function () {
6 // 上传图片
7   $( " #btnUpload " ).click(function () {
8 if ($( " #flUpload " ).val() == "" ) {
9 alert( " 请选择一个图片文件,再点击上传。 " );
10 return ;
11 }
12 $( ' #UpLoadForm ' ).ajaxSubmit({
13 success: function (html, status) {
14 var result = html.replace( " <pre> " , "" );
15 result = result.replace( " </pre> " , "" );
16 $( " #image " ).attr( ' src ' , result);
17 alert(result);
18 }
19 });
20 });
21 });

ashx 如下:

   
   
   
   
1 namespace TestMvc.Utility
2 {
3 /// <summary>
4 /// Summary description for PicUploadHander
5 /// </summary>
6   public class PicUploadHander : IHttpHandler
7 {
8
9 public void ProcessRequest(HttpContext context)
10 {
11 context.Response.ContentType = " text/plain " ;
12 // 验证上传的权限TODO
13 string _fileNamePath = "" ;
14 try
15 {
16 _fileNamePath = context.Request.Files[ 0 ].FileName;
17 // 开始上传
18 string _savedFileResult = UpLoadImage(_fileNamePath, context);
19 context.Response.Write(_savedFileResult);
20 }
21 catch
22 {
23 context.Response.Write( " 上传提交出错 " );
24 }
25 }

注:整个上传使用ajax 异步数据,同时jquery回调出上传成功后图片在服务器上的相对路径。总的来说此方式相对传统的上传图片方式要强一些。

你可能感兴趣的:(jquery,Ajax,ajaxSubmit,休闲,异步上传)