以一个小项目为例:

验证码:

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();
System.Drawing.Image img = new System.Drawing.Bitmap(, );//验证码图片大小 using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img))//取材
{
int sp = this.GetNumber(, , true);
graphics.FillRectangle(System.Drawing.Brushes.White, , , img.Width, img.Height);//填方
graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), , , img.Width - , img.Height - );//画方
for (int i = ; i < ; 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 + , -, );//由于字体的关系Point不准了,又是字符会出界,已经排除了一些字体了
System.Drawing.Font f = this.GetFont(, );
//画字符
graphics.DrawString(c, f, b, pf);//位置要一次间隔向后
sp += this.GetNumber(, , true);
}
using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
{
//画点:位置随即了
for (int j = ; j <= this.GetNumber(, , true); j++)
{
graphics.DrawString(".",
new System.Drawing.Font(this.GetFontName(), this.GetNumber(, , true)), b,
this.GetPointF(, , , ));
}
}
using (System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.FromName(this.GetColorName())))//彩色画刷
{
//画线:位置随即了
graphics.DrawLine(
new System.Drawing.Pen(b, this.GetNumber(, , true)),
this.GetPointF(, , , ), this.GetPointF(, , , ));
}
}
}
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(, FontNames.Count - , 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 = {'','','','','','','','','','',
'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(, charItems.Length - , 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(, , 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(, names.Length - , 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 + ) % ) == )
return a;
return ran.Next(min, max + );
}
}

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调用:

  验证码:<input type="text" name="txtCode" id="txtCode" /><img id="img" title="点击切换验证码" alt="验证码" src="VerifyCode.ashx" onclick="this.src='VerifyCode.ashx?ran='+new Date();" /><br />

上传文件:

<%@ 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 > && uploadFile.ContentType.IndexOf("image") > -)
{
//百度浏览器下只取了名字+后缀
string fileName = System.IO.Path.GetFileName(uploadFile.FileName);
//上传图片名称
string imgName = context.Session["IDCard"] + fileName.Substring(fileName.Length - );
//存到网站路径
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()) == )
{
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:

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/1eQmopOm

最新文章

  1. 成为OpenStack工程师
  2. WinForm常用属性
  3. [bzoj2743][HEOI2012]采花(树状数组+离线)
  4. OpenStack 企业私有云的若干需求(7):电信行业解决方案 NFV
  5. Android学习笔记(第二篇)View中的五大布局
  6. AIX配置时间服务器(NTP)
  7. php 环境变量收集
  8. Template 使用注意问题和范例
  9. javascript 典型闭包的用法
  10. textfile 属性
  11. FOJ 2203 单纵大法好
  12. 通过cmd命令行连接mysql数据库
  13. struts1.x mvc简单例程
  14. kubernetes进阶之二:概述
  15. Ubuntu18.04 VMwareTools安装方法
  16. Leetcode 665. Non-decreasing Array(Easy)
  17. 激活函数Sigmoid、Tanh、ReLu、softplus、softmax
  18. CodeForces - 1089G
  19. Git 的 WindowsXP安装
  20. [leetcode]367. Valid Perfect Square验证完全平方数

热门文章

  1. php数据缓存
  2. Ext TabPanel items高度宽度自适应
  3. 【转】javascript中this的四种用法
  4. java Exchanger 2
  5. 【Demo】微信上墙
  6. Wordpress引入多说插件
  7. strcpy之代码的健壮性与可维护性
  8. Caused by: java.lang.OutOfMemoryError: PermGen space.
  9. Top Five Communication Skills for Project Managers
  10. 提取日志中的json请求发送到另外一台机器