項目中用戶上傳總是少不了的,下面就主要的列舉一下表單上傳和ajax上傳!注意: context.Request.Files不適合對大文件進行操作,下面列舉的主要對于小文件上傳的處理!
資源下載:
一、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上傳吧!
新聞熱點
疑難解答
圖片精選