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


    1.生成随机图片验证码

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

    <div class="inputLine">
    <label>
    验证码</label> <input type="text" maxlength="4" autocomplete="off" name="verifycode" style="ime-mode: disabled;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;
    }
    }

    }

     

     

     

     

    3.解析html

    //采集期号,比赛,结果

    var maxIssuseCount = 2;

    //取期号
    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
    long tt = (DateTime.Now.Ticks - startTime.Ticks) / 10000;
    var url = "http://trade.500.com/bjdc/index.php";
    var encoding = Encoding.GetEncoding("gb2312");
    var content = PostManager.Get(url, encoding);

    //step 1 得到div内容
    var index = content.IndexOf("<option");
    content = content.Substring(index);
    index = content.IndexOf("</select>");
    content = content.Substring(0, index);

    var rows = content.Split(new string[] { "</option>" }, StringSplitOptions.RemoveEmptyEntries);

    var issuseStrList = new List<string>();
    foreach (var item in rows)
    {
    //var issuse = CutHtml(item).Replace("当前期", "").Replace(" ", "").Replace("第投注比例期","").Replace("第平均赔率期","");
    var issuse = CutHtml(item).Replace("当前期", "").Replace(" ", "");
    if (string.IsNullOrEmpty(issuse))
    continue;
    if (issuseStrList.Count >= maxIssuseCount)
    break;
    issuseStrList.Add(issuse);
    }

    foreach (var issuseStr in issuseStrList)
    {
    if (string.IsNullOrEmpty(issuseNumber))
    issuseNumber = issuseStr;

    var currentIssuseList = new List<KeyValuePair<DBChangeState, BJDC_Issuse>>();
    var currentMatchResultList = new List<KeyValuePair<DBChangeState, BJDC_MatchResult>>();
    var currentSFGGList = new List<KeyValuePair<DBChangeState, BJDC_Match_SFGG>>();
    var currentMatchResult_sfggList = new List<KeyValuePair<DBChangeState, BJDC_Match_SFGGResult>>();
    this.WriteLog(string.Format("开始采集期:{0}", issuseStr));

    var currentMatchList = BuildLeagueInfoCollectionFrom9188(issuseStr, getResult, out currentIssuseList, out currentMatchResultList, out currentSFGGList, out currentMatchResult_sfggList);
    issuseList.AddRange(currentIssuseList);//奖期
    leagueList.AddRange(currentMatchList);//比赛
    matchResultList.AddRange(currentMatchResultList);//结果
    matchsfggList.AddRange(currentSFGGList);
    matchResult_sfggList.AddRange(currentMatchResult_sfggList);

    this.WriteLog(string.Format("采集到期号{0},赛事队伍条数{1}条", issuseStr, leagueList.Count));
    this.WriteLog(string.Format("采集到期号{0},比赛结果{1}条", issuseStr, matchResultList.Count));
    this.WriteLog(string.Format("采集到期号{0},胜负过关赛事队伍条数{1}条", issuseStr, matchsfggList.Count));


    }

  • 相关阅读:
    suse系统FTP问题
    Oracle SQL编写注意事项
    EXP-00056: ORACLE error 6550 encountered报错;
    Linux 单网卡多 IP 的配置方法
    Authorized users only. All activity may be monitored and reported.
    使用jconsole检测linux服务器
    Suse系统用户不能登录报错
    性能测试介绍
    判断浏览器是否是手机端
    JSONP 跨域请求
  • 原文地址:https://www.cnblogs.com/csj007523/p/11442979.html
Copyright © 2020-2023  润新知