生成随机验证码,上传图片文件,解析HTML

1.生成随机图片验证码

 1.1 页面调用createvalidatecode 生成随机图片验证码方法;

<div class="inputLine">
<label>
验证码</label> <input type="text" maxlength="4" autocomplete="off" name="verifycode" style="ime-mode: disabled;width:40px;"
id="verifycode" class="reg_in_text" ><img onclick="refreshVerify()" alt="点击刷新" id="CheckCode" src="/home/createvalidatecode">
看不清?<a href="javascript:refreshVerify()">换一张</a>
</div>

 1.2 HomeController。createvalidatecode 实现方法;

//生成图片验证码并返回一个结果
public ValidateCodeGenerator CreateValidateCode()
{
var num = 0;
string randomText = SelectRandomNumber(5, out num);
Session["ValidateCode"] = num;
ValidateCodeGenerator vlimg = new ValidateCodeGenerator()
{
BackGroundColor = Color.FromKnownColor(KnownColor.LightGray),
RandomWord = randomText,
ImageHeight = 25,
ImageWidth = 100,
fontSize = 14,
};
return vlimg;
}

1.2.1 createvalidatecode 生成图片验证码类:

public class ValidateCodeGenerator : ActionResult
{
/// <summary>
/// 背景颜色
/// </summary>
public Color BackGroundColor { get; set; }
/// <summary>
/// 随机字符
/// </summary>
public string RandomWord { get; set; }
/// <summary>
/// 图片宽度
/// </summary>
public int ImageWidth { get; set; }
/// <summary>
/// 图片高度
/// </summary>
public int ImageHeight { get; set; }
/// <summary>
/// 字体大小
/// </summary>
public int fontSize { get; set; }

public override void ExecuteResult(ControllerContext context)
{
OnPaint(context);
}

static string[] FontItems = new string[] { "tahoma", "Verdana", "Consolas", "Times New Roman" };
static Brush[] BrushItems = new Brush[] { Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru };
static Color[] ColorItems = new Color[] { Color.Green, Color.Blue, Color.Gray, Color.Red, Color.Black, Color.Orange, Color.OrangeRed, Color.Silver };
private int _brushNameIndex;

Random _random = new Random(DateTime.Now.GetHashCode());

/// <summary>
/// 取一个随机字体
/// </summary>
/// <returns></returns>
private Font GetFont()
{
int fontIndex = _random.Next(0, FontItems.Length);
return new Font(FontItems[fontIndex], fontSize, GetFontStyle());
}

/// <summary>
/// 取一个随机字体样式
/// </summary>
/// <returns></returns>
private FontStyle GetFontStyle()
{
switch (DateTime.Now.Second % 2)
{
case 0:
return FontStyle.Regular | FontStyle.Bold;
case 1:
return FontStyle.Italic | FontStyle.Bold;
default:
return FontStyle.Regular | FontStyle.Bold | FontStyle.Strikeout;
}
}

/// <summary>
/// 取一个随机笔刷
/// </summary>
/// <returns></returns>
private Brush GetBrush()
{
_brushNameIndex = _random.Next(0, BrushItems.Length);
return BrushItems[_brushNameIndex];
}

/// <summary>
/// 获取随机颜色
/// </summary>
/// <returns></returns>
private Color GetColor()
{
int colorIndex = _random.Next(0, ColorItems.Length);
return ColorItems[colorIndex];
}

/// <summary>
/// 绘画背景色
/// </summary>
/// <param name="g"></param>
private void Paint_Background(Graphics g)
{
g.Clear(BackGroundColor);
}

/// <summary>
/// 绘画边框
/// </summary>
/// <param name="g"></param>
private void Paint_Border(Graphics g)
{
g.DrawRectangle(Pens.DarkGray, 0, 0, ImageWidth - 1, ImageHeight - 1);
}

/// <summary>
/// 绘画文字
/// </summary>
/// <param name="g"></param>
private void Paint_Text(Graphics g, string text)
{
int x = 1, y = 1;
Brush brush = GetBrush();
for (int i = 0; i < text.Length; i++)
{
x = ImageWidth / text.Length * i - 2;
y = _random.Next(0, 5);
g.DrawString(text.Substring(i, 1), GetFont(), brush, x, y);
}

}

/// <summary>
/// 绘画噪音点
/// </summary>
/// <param name="b"></param>
private void Paint_Stain(Bitmap b)
{
for (int n = 0; n < (ImageWidth * ImageHeight / 40); n++)
{
int x = _random.Next(0, ImageWidth);
int y = _random.Next(0, ImageHeight);
b.SetPixel(x, y, GetColor());
}
}

/// <summary>
/// 画笔事件
/// </summary>
/// <param name="context"></param>
private void OnPaint(ControllerContext context)
{
Bitmap oBitmap = null;
Graphics g = null;

try
{
oBitmap = new Bitmap(ImageWidth, ImageHeight);
g = Graphics.FromImage(oBitmap);

Paint_Background(g);
Paint_Text(g, RandomWord);
Paint_Stain(oBitmap);
//Paint_Border(g);

context.HttpContext.Response.ContentType = "image/gif";
oBitmap.Save(context.HttpContext.Response.OutputStream, ImageFormat.Gif);
g.Dispose();
oBitmap.Dispose();
}
catch
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.Write("Err!");
context.HttpContext.Response.End();
}
finally
{
if (null != oBitmap)
oBitmap.Dispose();
if (null != g)
g.Dispose();
}
}

}

2 图片,文件的上传

public class UpLoadController : BaseController
{
[HttpPost]
public ContentResult UpLoadImage()
{
try
{
var file = Request.Files["imgFile"];
string nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string resourceSiteUrl = ConfigurationManager.AppSettings["ResourceSiteUrl"].ToString();
string resourceSitePostUrl = ConfigurationManager.AppSettings["ResourceSitePostUrl"].ToString();
string upLoadFile = ConfigurationManager.AppSettings["UpLoadFile"].ToString();
string upLoadPostPath = ConfigurationManager.AppSettings["UpLoadPostPath"].ToString();
nameImg += file.FileName.Substring(file.FileName.LastIndexOf(".")).ToLower();
string url = string.Format("{0}{1}{2}", resourceSiteUrl, upLoadFile, nameImg);

upLoadFile = "/" + ConfigurationManager.AppSettings["WebSiteEName"].ToString() + upLoadFile;

string postUrl = string.Format("{0}{1}?filename={2}&upLoadFile={3}", resourceSitePostUrl, upLoadPostPath, nameImg, upLoadFile);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.AllowAutoRedirect = false;
request.ContentType = "multipart/form-data";
byte[] bytes = new byte[file.InputStream.Length];
file.InputStream.Read(bytes, 0, (int)file.InputStream.Length);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse respon = (HttpWebResponse)request.GetResponse();
Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = url;
return Content(System.Web.Helpers.Json.Encode(hash), "text/html; charset=UTF-8");

}
catch (Exception ex)
{
var writer = Common.Log.LogWriterGetter.GetLogWriter();
writer.Write("UploadFiles", "-Admin_Upload", ex);
throw ex;
}
}

public string UpLoadFile(string fromFilePath, string toFilePath, string fileName)
{
fromFilePath = "/Xml/test.xml";
toFilePath = "/UpLoad/uploadimages/";
try
{
FileInfo fi = new FileInfo(fromFilePath);
FileStream fs = fi.OpenRead();
string resourceSiteUrl = ConfigurationManager.AppSettings["ResourceSiteUrl"].ToString();

string postUrl = resourceSiteUrl + "/UpLoad/upload_json.aspx" + "?filename=" + fileName + "&upLoadFile=" + toFilePath;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.AllowAutoRedirect = false;
request.ContentType = "multipart/form-data";
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);

request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse respon = (HttpWebResponse)request.GetResponse();
Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = toFilePath + fileName;

//return Content(System.Web.Helpers.Json.Encode(hash), "text/html; charset=UTF-8");
return "";

}
catch (Exception ex)
{
throw ex;
}
}

}

猜你喜欢

转载自www.cnblogs.com/csj007523/p/11442979.html