HTML加一般处理程序实现文件上传

来源:互联网 发布:java invoke方法 编辑:程序博客网 时间:2024/04/29 16:50

HTML代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body>    <form action="Upload.ashx" method="post" enctype="multipart/form-data">    选择要上传的图片:<input type="file" name="fileUp" />    <input type="submit" value="上传" /></form></body></html>

后台程序:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Drawing;using System.Drawing.Imaging;namespace UploadDemo{    /// <summary>    /// Summary description for Upload    /// </summary>    public class Upload : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            //获得浏览器端 传过来 第一个文件选择框的数据            HttpPostedFile hpFile = context.Request.Files[0];                        //要保存的目录路径            string filePath = "upload";            //判断 上传文件数据的长度是否>0            if (hpFile.ContentLength > 0)            {                //获得上传上来的文件名称                string fileName = System.IO.Path.GetFileName(hpFile.FileName);                //获得 要保存的物理路径                filePath = context.Server.MapPath(filePath + "/" + fileName);                //将上传来的 文件数据 保存在 对应的 物理路径上                hpFile.SaveAs(filePath);                //如果上传上来的是图片文件数据                if (hpFile.ContentType.IndexOf("image") > -1)                {                    //将上传上来的文件对象里的 数据流 转成 图片对象                    using (Image img = Image.FromStream(hpFile.InputStream))                    {                        //创建缩略图对象                        using (Bitmap thumbImg = new Bitmap(120, 40))                        {                            //创建 【画家】对象,并告诉他要在缩略图上作画                            using (Graphics g = Graphics.FromImage(thumbImg))                            {                                //将 原图 img 画在 缩略图 thumbImg上                                //第一个长方形参数:要把原图 画成多大                                //第二个长方形参数:要画原图的哪个部分(要把原图的哪个部分画到缩略图上)                                g.DrawImage(img, new Rectangle(0, 0, thumbImg.Width, thumbImg.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);                                string thumbImgPath = context.Server.MapPath("upload/thumb" + fileName);                                thumbImg.Save(thumbImgPath);                                context.Response.Write("制作小图成功:" + "/thumb" + fileName);                            }                        }                    }                }                context.Response.Write("上传成功:" + hpFile.FileName);            }            else            {                context.Response.Write("还米有选择要上传的文件!");            }        }        public bool IsReusable        {            get            {                return false;            }        }    }}

注:源代码来自传智播客讲师“邹华栋”老师!




原创粉丝点击