asp.net 怎么把远程图片保存为本地文件?

  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using System.IO;
  5. using System.Net;
  6. namespace BookStore.Component
  7. {
  8. /// <summary>
  9. /// 
  10. /// </summary>
  11. public class DownloadUtil : System.Web.UI.Page
  12. {
  13. public DownloadUtil(){}
  14. private string [] GetImgTag(string htmlStr)
  15. {
  16. Regex regObj = new Regex("<img.+?>",RegexOptions.Compiled|RegexOptions.IgnoreCase);
  17. string [] strAry = new string [regObj.Matches(htmlStr).Count] ;
  18. int i = 0;
  19. foreach (Match matchItem in regObj.Matches(htmlStr))
  20. {
  21. strAry[i] = GetImgUrl(matchItem.Value);
  22. i++;
  23. }
  24. return strAry ;
  25. }
  26. private string GetImgUrl(string imgTagStr)
  27. {
  28. string str = "";
  29. Regex regObj = new Regex("http://.+?.gifhttp://.+?.jpghttp://.+?.jpeghttp://.+?.bmp",
  30. RegexOptions.Compiled|RegexOptions.IgnoreCase);
  31. foreach (Match matchItem in regObj.Matches(imgTagStr))
  32. {
  33. str = matchItem.Value;
  34. }
  35. return str;
  36. }
  37. public string SaveUrlPics(string strHTML)
  38. {
  39. string [] imgurlAry = GetImgTag(strHTML);
  40. try
  41. {
  42. for(int i=0 ; i<imgurlAry.Length ; i++)
  43. {
  44. WebRequest req=WebRequest.Create(imgurlAry[i]);
  45. string preStr=System.DateTime.Now.ToString()+"_";
  46. preStr=preStr.Replace("-","_");
  47. preStr=preStr.Replace(":","_");
  48. preStr=preStr.Replace(" ","_");
  49. WebClient wc=new WebClient();
  50. wc.DownloadFile(imgurlAry[i],Server.MapPath("images")+"/"
  51. +preStr+imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/")+1));
  52. strHTML=strHTML.Replace(imgurlAry[i],"images/"
  53. +preStr+imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/")+1));
  54. }
  55. return strHTML;
  56. }
  57. catch(Exception ex)
  58. {
  59. return ex.Message;
  60. }
  61. }
  62. }
  63. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值