asp.net上传文件
1.需要设置html页面表单元素的enctype属性为 "multipart/form-data"
1 public void ProcessRequest(HttpContext context) 2 { 3 context.Response.ContentType = "text/html"; 4 HttpPostedFile postedFile = context.Request.Files["uploadFile"]; 5 if (postedFile!=null)//判断上传的文件是否为空 6 { 7 //通过后缀名判断文件类型 8 string fileExt=Path.GetExtension(Path.GetFileName(postedFile.FileName)); 9 if (fileExt==".jpg") 10 { 11 //创建文件夹 12 string dirPath = "Image/" + DateTime.Now.Year + "年/" + DateTime.Now.Month + "月/" + DateTime.Now.Day + "日/"; 13 if (Directory.Exists(dirPath)==false) 14 { 15 Directory.CreateDirectory(context.Request.MapPath(dirPath)); 16 } 17 string fileName = Guid.NewGuid().ToString()+fileExt;//防止上传的文件重复 18 //postedFile.SaveAs(context.Request.MapPath(dirPath+fileName));//保存文件 19 20 //添加水印 21 using (Image image=Image.FromStream(postedFile.InputStream))//从文件流创建 InputStream是上传文件的流 22 { 23 using (Bitmap map = new Bitmap(image.Width,image.Height))//应该是图片的宽和图片的高 24 { 25 using (Graphics g=Graphics.FromImage(map))//Bitmap继承自Image 26 { 27 //先将图片画到画布上 28 g.DrawImage(image,new Rectangle(0,0,image.Width,image.Height)); 29 //画文字 30 g.DrawString("zz.o3o.ac.cn:97", new Font("微软雅黑",14.0f, FontStyle.Underline), Brushes.Red, new PointF(image.Width-100,image.Height-30)); 31 map.Save(context.Request.MapPath(dirPath + fileName));//保存图片 32 } 33 } 34 } 35 context.Response.Write("<html><head></head><body><img src='" + dirPath + fileName + "'/></body></html>"); 36 //最后存入数据库 (文件的路径)略. 37 } 38 else 39 { 40 context.Response.Write("文件格式不正确"); 41 } 42 } 43 else 44 { 45 context.Response.Write("请选择文件"); 46 } 47 }

浙公网安备 33010602011771号