您好,登錄后才能下訂單哦!
這篇文章給大家介紹如何在asp.net中利用ashx文件上傳文件,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
方法一:Form表單提交
html代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>上傳文件</title> <script src="Scripts/jquery-1.11.3.min.js"></script> </head> <body> <form action="UploadHandler.ashx" method="post" enctype="multipart/form-data"> <input id="file_upload" name="file_upload" type="file" /> <input id="btn_upload" type="submit" value="上傳" /> </form> </body> </html>
UploadHandler.ashx代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1 { /// <summary> /// UploadHandler 的摘要說明 /// </summary> public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile file = context.Request.Files["file_upload"]; string filePath = context.Server.MapPath("~/UploadFiles/") + System.IO.Path.GetFileName(file.FileName); file.SaveAs(filePath); context.Response.Write("上傳文件成功"); } public bool IsReusable { get { return false; } } } }
該方法雖然能夠實現文件的上傳,但是form表單提交之后整個頁面就刷新了,如果要無刷新上傳文件的話,就要使用ajax了。
方法二:jquery + ajax無刷上傳
html代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>上傳文件</title> <script src="Scripts/jquery-1.11.3.min.js"></script> </head> <body> <input id="file_upload" name="file_upload" type="file" /> <input id="btn_upload" type="button" value="上傳" /> <script> $(document).ready(function () { $('#btn_upload').bind('click', function () { var formData = new FormData(); formData.append('upload_file', $('#file_upload')[0].files[0]); $.ajax({ url: 'UploadHandler.ashx', type: 'post', data: formData, contentType: false, processData: false, success: function (msg) { if (msg == "Yes") { alert('文件上傳成功'); } else { alert('文件上傳失敗'); } } }) }); }); </script> </body> </html>
UploadHandler.ashx代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1 { /// <summary> /// UploadHandler 的摘要說明 /// </summary> public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; if (context.Request.Files.Count > 0) { HttpPostedFile file = context.Request.Files["upload_file"]; string filePath = context.Server.MapPath("~/UploadFiles/") + System.IO.Path.GetFileName(file.FileName); file.SaveAs(filePath); context.Response.Write("Yes"); } else { context.Response.Write("No"); } } public bool IsReusable { get { return false; } } } }
關于如何在asp.net中利用ashx文件上傳文件就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。