context.Request.Files不适合对大文件进行操作,下面列举的主要对于小文件上传的处理!
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); }
时间: 2024-11-05 16:23:57