温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

asp.net中表单上传功能如何实现ajax文件异步上传

发布时间:2021-07-06 10:57:22 来源:亿速云 阅读:226 作者:小新 栏目:web开发

这篇文章主要为大家展示了“asp.net中表单上传功能如何实现ajax文件异步上传”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“asp.net中表单上传功能如何实现ajax文件异步上传”这篇文章吧。

资源下载:

一、jQuery官方下载地址:https://jquery.com/download/ 

一.表单上传:

html客户端部分:

<form action="upload.ashx" method="post" enctype="multipart/form-data">     选择文件:<input type="file" name="file1" /><br />     <input type="submit" value="上传" />   </form>

一般处理程序服务器端:

public void ProcessRequest(HttpContext context)     {       context.Response.ContentType = "text/plain";       HttpPostedFile file1 = context.Request.Files["file1"];       helper.uploadFile(file1, "~/upload/");//这里就是对相应方法进行调用       context.Response.Write("ok");//提示执行成功     }

上传代码的封装:

/// <summary>     /// 上传图片     /// </summary>     /// <param name="file">通过form表达提交的文件</param>     /// <param name="virpath">文件要保存的虚拟路径</param>     public static void uploadImg(HttpPostedFile file,string virpath)     {            if (file.ContentLength > 1024 * 1024 * 4)       {         throw new Exception("文件不能大于4M");       }       string imgtype = Path.GetExtension(file.FileName);       if(imgtype!=".jpg"&&imgtype!=".jpeg") //图片类型进行限制       {         throw new Exception("请上传jpg或JPEG图片");       }       using (Image img = Bitmap.FromStream(file.InputStream))       {         string savepath = HttpContext.Current.Server.MapPath(virpath+file.FileName);         img.Save(savepath);       }     }     /// <summary>     /// 上传文件     /// </summary>     /// <param name="file">通过form表达提交的文件</param>     /// <param name="virpath">文件要保存的虚拟路径</param>     public static void uploadFile(HttpPostedFile file, string virpath)     {       if (file.ContentLength > 1024 * 1024 * 6)       {         throw new Exception("文件不能大于6M");       }       string imgtype = Path.GetExtension(file.FileName);       //imgtype对上传的文件进行限制       if (imgtype != ".zip" && imgtype != ".mp3")       {         throw new Exception("只允许上传zip、rar....文件");       }       string dirFullPath= HttpContext.Current.Server.MapPath(virpath);       if (!Directory.Exists(dirFullPath))//如果文件夹不存在,则先创建文件夹       {         Directory.CreateDirectory(dirFullPath);       }       file.SaveAs(dirFullPath + file.FileName);     }

二.Ajax文件异步上传:

注明:既然有了表单上传为什么又要ajax上传呢?因为表单上传过程中,整个页面就刷新了!ajax异步上传就可以达到只刷新局部位置,下面就简单看看ajax上传吧!

html客户端部分:

<head>  <script src="jquery-2.1.4.js"></script>  <script>   $(function () {    $("#upload").click(function () {     $("#imgWait").show();     var formData = new FormData();     formData.append("myfile", document.getElementById("file1").files[0]);      $.ajax({      url: "upload.ashx",      type: "POST",      data: formData,      /**      *必须false才会自动加上正确的Content-Type      */      contentType: false,      /**      * 必须false才会避开jQuery对 formdata 的默认处理      * XMLHttpRequest会对 formdata 进行正确的处理      */      processData: false,      success: function (data) {       if (data.status == "true") {        alert("上传成功!");       }       if (data.status == "error") {        alert(data.msg);       }       $("#imgWait").hide();      },      error: function () {       alert("上传失败!");       $("#imgWait").hide();      }     });    });   });  </script> </head> <body>    选择文件:<input type="file" id="file1" /><br />   <input type="button" id="upload" value="上传" />   <img src="wait.gif"  id="imgWait" />  </body>

一般处理程序服务器端:

public void ProcessRequest(HttpContext context)   {    context.Response.ContentType = "text/html";    if (context.Request.Files.Count > 0)    {     HttpPostedFile file1 = context.Request.Files["myfile"];     helper.uploadFile(file1, "~/upload/"); //这里引用的是上面封装的方法     WriteJson(context.Response, "true", "");    }    else    {     WriteJson(context.Response, "error", "请选择要上传的文件");    }   }

json代码封装:

public static void WriteJson(HttpResponse response,       string status1, string msg1, object data1 = null)     {       response.ContentType = "application/json";       var obj = new { status = status1, msg = msg1, data = data1 };       string json = new JavaScriptSerializer().Serialize(obj);       response.Write(json);     }

以上是“asp.net中表单上传功能如何实现ajax文件异步上传”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI