1. 程式人生 > >普通檔案的上傳(表單上傳和ajax檔案非同步上傳)

普通檔案的上傳(表單上傳和ajax檔案非同步上傳)

一.表單上傳:

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" style="display:none" 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); }