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

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

WebClient wc = new WebClient();  //

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

  

ContractedBlock.gif ExpandedBlockStart.gif 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=""  ....>

ContractedBlock.gif ExpandedBlockStart.gif 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;

ContractedBlock.gif ExpandedBlockStart.gif 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 }

转载于:https://www.cnblogs.com/shengxiang/archive/2011/05/31/2064936.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值