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

来源:互联网 发布:linux安装adobe flash 编辑:程序博客网 时间:2024/04/29 15:58
  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. }