html前端页面代码:
如果要上传,就必须 设置 表单 method=post,而且 enctype=multipart/form-data ,
一旦设置了 enctype=multipart/form-data,那么浏览器生成请求报文的时候,就会生成 数据分割符并且更换 请求报文体 的数据 组织格式(使用 分隔符 来 分开不同 html 表单控件的 内容)
<body> <form method="post" action="Upload.ashx" enctype="multipart/form-data"> <input type="file" name="file01" /> <input type="file" name="file02" /> <input type="submit" value="上传" /> </form> </body>
上传大图和缩略图,并且大图上添加水印
public void ProcessRequest(HttpContext context) { System.Text.StringBuilder sbMsg = new System.Text.StringBuilder(200); //浏览器端上传文件的集合:Request.Files //1.遍历所有上传来的文件 for (int i = 0; i < context.Request.Files.Count; i++) { HttpPostedFile file = context.Request.Files[i]; //判断文件大小 if (file.ContentLength > 0) { //判断上传的文件 是否 为 图片 //通过 判断文件的 类型 if (file.ContentType.Contains("image/")) { //2.为图片加水印 //2.1获取图片文件流,并封装到 C# 的 Image对象中 方便操作 using (Image img = Image.FromStream(file.InputStream)) { string strImgName = file.FileName; string strThmImbName = ""; GetRandomName(ref strImgName,ref strThmImbName); //2.2生成缩略图 using (Image imgThumb = new Bitmap(200,100)) { //2.2.1生成 画家对象,要它在 缩略图上作画 using (Graphics g = Graphics.FromImage(imgThumb)) { // 原图 , 要把原图缩略成多大 , 取原图的哪个部分 来缩略 ,单位(像素) g.DrawImage(img, new Rectangle(0, 0, imgThumb.Width, imgThumb.Height), new RectangleF(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); } //先获取物理路径 string phyPath = context.Request.MapPath("/upload/" + strThmImbName); //保存 imgThumb.Save(phyPath); } //3.读取 水印 图片,画到 上传的图片上 using (Image imgWater = Image.FromFile(context.Server.MapPath("/img/logo.jpg"))) { using (Graphics g = Graphics.FromImage(img)) { //g.DrawString(".Net上传图片", new Font("微软雅黑", 14), Brushes.Red, 0, 0); //将 水印图片 画到 上传的图上 g.DrawImage(imgWater, 0, 0); } //先获取物理路径 string phyPath = context.Request.MapPath("/upload/" + strImgName); //保存 img.Save(phyPath); sbMsg.AppendLine(strImgName + "<br/>"); } } //file.SaveAs(phyPath); } } } context.Response.Write("保存成功啦:" + sbMsg.ToString()); } void GetRandomName(ref string imgName,ref string thumbName) { string fileName =Guid.NewGuid().ToString(); string extention = System.IO.Path.GetExtension(imgName); //生成原图名 imgName = fileName + extention; //生成缩略图名 thumbName = fileName + "+thm" + extention; }
原文:http://blog.csdn.net/ankeyuan/article/details/23189319