发布新闻,把外链接的图片下载到本地

时间:2022-11-12 09:03:59

Path.GetExtension("string.jpg")    // 获得字符串的扩展名

WebClient wc = new WebClient();  //

wc.DownloadFile("http://img.style.20011212.jpg","Path");  // 此方法将指定的URL资源下载到本地

  

发布新闻,把外链接的图片下载到本地发布新闻,把外链接的图片下载到本地View Code
   
   
   
1 private string SaveUrlPics( string strHtml, string path, string nowyymm, string nowdd)
2 {
         //strHtml 内容
3 string [] imgurlAry = GetImgTag(strHtml); // 获得内容中的 外链地址 数组
4         
5 try
6 {
7 foreach ( string t in imgurlAry)
8 {
9 string fileName = DateTime.Now.ToString( " yyyyMMddhhmmssfffff " ).Substring( 0 , 17 );
10 var wc = new WebClient();
11 if (t == "" ) continue ;
12 wc.DownloadFile(t, HttpContext.Current.Server.MapPath(path) + " / " + fileName + t.Substring(t.LastIndexOf( " . " )));
13
14 // 替换原图片地址
15   string imgPath = " /FileUpload/ " + nowyymm + " / " + nowdd;
             // 替换内容中图片的 外链接 地址

16 strHtml = strHtml.Replace(t, imgPath + " / " + fileName + t.Substring(t.LastIndexOf( " . " )));
17
18 }
19 }
20 catch (Exception ex)
21 {
22 return ex.Message;
23 }
24
25 return strHtml;
26
27 }

用正则表达式 匹配 提取内容中的 <img  > 标签    返回  <img src=""  ....>

发布新闻,把外链接的图片下载到本地发布新闻,把外链接的图片下载到本地View Code
   
   
   
1 /// <summary>
2 /// 获取内容中的图片信息
3 /// </summary>
4 /// <param name="htmlStr"></param>
5 /// <returns></returns>
6   private string [] GetImgTag( string htmlStr)
7 {
8 var regObj = new Regex( " <img.+?> " , RegexOptions.Compiled | RegexOptions.IgnoreCase);
9 var strAry = new string [regObj.Matches(htmlStr).Count];
10 int i = 0 ;
11 foreach (Match matchItem in regObj.Matches(htmlStr))
12 {
13 strAry[i] = GetImgUrl(matchItem.Value);
14 i ++ ;
15 }
16 return strAry;
17 }

用正则表达式匹配 传入的  <img  > 标签   获取 链接 地址  返回 http://img.sina.2100.jpg;

发布新闻,把外链接的图片下载到本地发布新闻,把外链接的图片下载到本地View Code
   
   
   
1 /// <summary>
2 /// 获取图片URL地址
3 /// </summary>
4 /// <param name="imgTagStr"></param>
5 /// <returns></returns>
6   private static string GetImgUrl( string imgTagStr)
7 {
8 var str = "" ;
9 var regObj = new Regex( " http://.+.(?:jpg|gif|bmp|png) " , RegexOptions.Compiled | RegexOptions.IgnoreCase);
10 foreach (Match matchItem in regObj.Matches(imgTagStr))
11 {
12 str = matchItem.Value;
13 }
14 return str;
15 }