ASP.NET的通常處理程序對圖片文件的基本操做

以一個小項目爲例:html

驗證碼:數據庫

public class VerifyCodeHelper
{
    public VerifyCodeHelper()
    {
        this.ran = new Random();
    }

    private Random ran = null;
    private string verifyCode;
    /// <summary>
    /// 驗證碼
    /// </summary>
    public string VerifyCode
    {
        get { return verifyCode; }
        set { verifyCode = value; }
    }


    /// <summary>
    /// 獲取驗證碼圖片對象
    /// </summary>
    /// <returns>System.Drawing.Image </returns>
    public System.Drawing.Image GetVerifyCode()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder(5);
        System.Drawing.Image img = new System.Drawing.Bitmap(105, 50);//驗證碼圖片大小

        using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img))//取材
        {
            int sp = this.GetNumber(1, 3, true);
            graphics.FillRectangle(System.Drawing.Brushes.White, 0, 0, img.Width, img.Height);//填方
            graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, img.Width - 1, img.Height - 1);//畫方
            for (int i = 1; i < 5; i++)//5個字符
            {
                using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色畫刷
                {
                    string c = string.Empty;
                    sb.Append((c = this.GetChar().ToString()));
                    System.Drawing.PointF pf = this.GetPointF(sp, sp + 6, -5, 2);//因爲字體的關係Point不許了,又是字符會出界,已經排除了一些字體了
                    System.Drawing.Font f = this.GetFont(34, 41);
                    //畫字符
                    graphics.DrawString(c, f, b, pf);//位置要一次間隔向後
                    sp += this.GetNumber(16, 20, true);
                }
                using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色畫刷
                {
                    //畫點:位置隨即了
                    for (int j = 1; j <= this.GetNumber(8, 16, true); j++)
                    {
                        graphics.DrawString(".",
                            new System.Drawing.Font(this.GetFontName(), this.GetNumber(6, 8, true)), b,
                            this.GetPointF(1, 99, 1, 39));
                    }
                }
                using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色畫刷
                {
                    //畫線:位置隨即了
                    graphics.DrawLine(
                        new System.Drawing.Pen(b, this.GetNumber(1, 2, true)),
                        this.GetPointF(1, 99, 1, 39), this.GetPointF(1, 99, 1, 39));
                }
            }
        }
        this.verifyCode = sb.ToString();
        return img;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>FontName</returns>
    private string GetFontName()
    {
        System.Collections.Generic.List<string> Not = new System.Collections.Generic.List<string>();
        string[] not = { "BatangChe", "DotumChe", "GulimChe", "GungsuhChe", "Angsana New", "AngsanaUPC", "Arabic Typesetting",
                           "Browallia New", "BrowalliaUPC", "Cordia New", "CordiaUPC", "DaunPenh", "DilleniaUPC", "EucrosiaUPC",
                           "FreesiaUPC", "Gabriola","IrisUPC", "JasmineUPC","KodchiangUPC", "Kokila","LilyUPC", "Microsoft Himalaya",
                           "Microsoft Uighur", "Microsoft Yi Baiti","MoolBoran", "Nyala","Sakkal Majalla", "Segoe Script","Shonar Bangla",
                           "Utsaah","Wingdings","Cambria Math","Narkisim","Batang","Lucida Console","MT Extra","Dotum","Marlett",
                       "Mangal","Malgun Gothic","Segoe Print","Lucida Sans Unicode","DokChampa","Webdings","Latha","MV Boli"};
        Not.AddRange(not);
        System.Collections.Generic.List<string> FontNames = new System.Collections.Generic.List<string>();
        foreach (System.Drawing.FontFamily item in System.Drawing.FontFamily.Families)
        {
            if (!Not.Contains(item.Name))
                FontNames.Add(item.Name);
        }
        return FontNames[this.GetNumber(1, FontNames.Count - 1, true)];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="xmin"></param>
    /// <param name="xmax"></param>
    /// <param name="ymin"></param>
    /// <param name="ymax"></param>
    /// <returns>PointF</returns>
    private System.Drawing.PointF GetPointF(int xmin, int xmax, int ymin, int ymax)
    {
        return new System.Drawing.PointF(this.GetNumber(xmin, xmax, true), this.GetNumber(ymin, ymax, true));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>char</returns>
    private char GetChar()
    {
        char[] charItems = {'0','1','2','3','4','5','6','7','8','9',
                               'a','b','c','d','e','f','g','h','i','j','k','l','m',
                               'n','o','p','q','r','s','t','u','v','w','x','y','z',
                               'A','B','C','D','E','F','G','H','I','J','K','L','M',
                               'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
        return charItems[this.GetNumber(0, charItems.Length - 1, true)];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns>Font</returns>
    private System.Drawing.Font GetFont(int min, int max)
    {
        return new System.Drawing.Font(
            this.GetFontName(),
            this.GetNumber(min, max, true),
            (System.Drawing.FontStyle)this.GetNumber(0, 2, true),
            System.Drawing.GraphicsUnit.Pixel);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns>ColorName</returns>
    private string GetColorName()
    {
        string[] names ={ "Aqua","Black","Blue","BlueViolet","Brown",
                          "Crimson","DarkBlue","DarkGreen","DarkMagenta","DarkOliveGreen",
                          "DarkOrange","DarkOrchid","DarkRed","DarkSlateBlue",
                          "DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue",
                          "Firebrick","Green","Indigo","LightGreen","Magenta",
                          "MediumBlue","Maroon","Navy","OrangeRed","Purple",
                          "Red","RoyalBlue","Salmon","SeaGreen","Sienna","SlateBlue","Violet"};
        return names[this.GetNumber(0, names.Length - 1, true)];
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <param name="isContinue"></param>
    /// <returns>int</returns>
    private int GetNumber(int min, int max, bool isContinue)
    {
        int a;
        while (!isContinue)
            if ((a = ran.Next(min, max + 1) % 2) == 0)
                return a;
        return ran.Next(min, max + 1);
    }
}

ashx文件:瀏覽器

<%@ WebHandler Language="C#" Class="VerifyCode" %>

using System;
using System.Web;

public class VerifyCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        if (context.Request.UrlReferrer != null)
        {
            VerifyCodeHelper vc = new VerifyCodeHelper();
            using (System.Drawing.Image img = vc.GetVerifyCode())
            {
                img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }

            context.Response.SetCookie(new HttpCookie("code", vc.VerifyCode));
            //context.Session["code"] = vc.VerifyCode;}
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

html調用:dom

  驗證碼:<input type="text" name="txtCode" id="txtCode" /><img id="img" title="點擊切換驗證碼" alt="驗證碼" src="VerifyCode.ashx" onclick="this.src='VerifyCode.ashx?ran='+new Date();" /><br />

上傳文件:post

<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.Web.SessionState;
public class Upload : IHttpHandler, IRequiresSessionState
{
    private BLL.TransferAction transfer = null;
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        if (context.Session["name"] != null)
        {
            if (context.Request.Url.Query == "?ID=" + context.Session["IDCard"])
            {
                HttpPostedFile uploadFile = context.Request.Files["txtUpload"];

                if (uploadFile.ContentLength > 0 && uploadFile.ContentType.IndexOf("image") > -1)
                {
                    //百度瀏覽器下只取了名字+後綴
                    string fileName = System.IO.Path.GetFileName(uploadFile.FileName);
                    //上傳圖片名稱
                    string imgName = context.Session["IDCard"] + fileName.Substring(fileName.Length - 4);
                    //存到網站路徑
                    uploadFile.SaveAs(context.Server.MapPath(context.Session["OImg"].ToString()));
                    //臨時Session  小圖片路徑名稱
                    string imgSName = "s" + imgName;
                    context.Session["imgSPath"] = "Upload/" + imgSName;
                    //生成小圖
                    using (System.Drawing.Image img = ImageHelper.GetSImg(context.Server.MapPath("Upload/" + imgName)))
                    {
                        img.Save(context.Server.MapPath(context.Session["imgSPath"].ToString()));
                    }
                    transfer = new BLL.TransferAction();
                    //存入數據庫URL
                    if (transfer.Update(context.Session["IDCard"].ToString(), context.Session["imgSPath"].ToString()) == 1)
                    {
                        InfoHelper.Identity.PortraitURL = context.Session["imgSPath"].ToString();
                        context.Response.Write("文件:" + fileName + "保存成功。<div style=\"color:Red;size:25px;width:30px;height:30px;\" id=\"Info\">3</div><script>var sec=3;setInterval(function(){if(sec>0){document.getElementById('Info').innerHTML=sec;sec--;}else{window.location='MyInfoList.ashx';}},1000);</script>" + "秒後跳轉。");
                    }
                    else
                    {
                        context.Response.Write("文件:" + fileName + "保存失敗。");
                    }
                }
            }
            else
            {
                string con = IOHelper.CreateInstance(context).GetFileContent("Upload.html");
                context.Response.Write(con.Replace("XXXXXX", context.Session["IDCard"].ToString()));
            }
        }
        else
            context.Response.Redirect("HomePage.html");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

html文件:字體

<body>
    <form action="Upload.ashx?ID=XXXXXX" method="post" enctype="multipart/form-data">
        <input type="file" name="txtUpload"  />
        <input type="submit" value="上傳" />
    </form>
</body

下載文件:網站

<%@ WebHandler Language="C#" Class="DownLoad" %>

using System;
using System.Web;

public class DownLoad : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        if (context.Session["name"] != null && context.Request.Url.ToString().Contains("DownLoad.ashx"))
        {            
            context.Response.AddHeader("Content-Disposition", "attachment;filename="+context.Request.QueryString["filename"]);
            context.Response.WriteFile(context.Server.MapPath(context.Session["IdentityCard"].ToString()));
        }
        else
            context.Response.Redirect("HomePage.html");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

html:ui

string contextY = "<img src=\"" + context.Session["IdentityCard"].ToString() + "\" alt=\"" + context.Session["name"].ToString() + "\"/><br/><a href='DownLoad.ashx?filename=\"" + context.Session["IdentityCard"].ToString() + "\"'>下載</a>

相關項目文件:http://pan.baidu.com/s/1eQmopOmthis

相關文章
相關標籤/搜索