自動下載網頁中圖片到服務器指定位置

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace zhang.Common
{
    public class HanlerFiles
    {
        private string GetImgTag(string htmlStr)
        {
            Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            string strAry = new string[regObj.Matches(htmlStr).Count];
            int i = 0;
            foreach (Match matchItem in regObj.Matches(htmlStr))
            {
                strAry[i] = GetImgUrl(matchItem.Value);
                i++;
            }
            return strAry;
        }

        private string GetImgUrl(string imgTagStr)
        {
            string str = "";
            Regex regObj = new Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            foreach (Match matchItem in regObj.Matches(imgTagStr))
            {
                str = matchItem.Value;
            }
            return str;
        }
        /**//// <summary>
        /// 根椐Html內空自動識別圖像文件,並下載到服務器指定目錄
        /// </summary>
        /// <param name="strHTML"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public int SaveUrlPics(ref string strHTML, string path)
        {
            string imgurlAry = GetImgTag(strHTML);
            try
            {
                for (int i = 0; i < imgurlAry.Length; i++)
                {
                    //WebRequest req = WebRequest.Create(imgurlAry[i]);
                    string preStr = System.DateTime.Now.ToString() + "_";
                    preStr = preStr.Replace("-", "");
                    preStr = preStr.Replace(":", "");
                    preStr = preStr.Replace(" ", "");
                    WebClient wc = new WebClient();
                    wc.DownloadFile(imgurlAry[i], HttpContext.Current.Server.MapPath(path) + "/" + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
                    strHTML = strHTML.Replace(imgurlAry[i], path + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
                }
                
            }
            catch (Exception ex)
            {
                //return ex.Message;
            }
            return imgurlAry.Length;
        }

    }
}
本文來自網學(http://myeducs.cn),轉載請註明出處:http://myeducs.cn/lunwen-resource/Net-biancheng/zidongshibie-HTML-daimalidetupian-like-bing-download-daofuwuqidezhidingmuluyuanma/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章