asp.net 怎么把远程图片保存为本地文件?
来源:互联网 发布:linux安装adobe flash 编辑:程序博客网 时间:2024/04/29 15:58
- using System;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.IO;
- using System.Net;
- namespace BookStore.Component
- {
- public class DownloadUtil : System.Web.UI.Page
- {
- public DownloadUtil(){}
- 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://.+?.gifhttp://.+?.jpghttp://.+?.jpeghttp://.+?.bmp",
- RegexOptions.Compiled|RegexOptions.IgnoreCase);
- foreach (Match matchItem in regObj.Matches(imgTagStr))
- {
- str = matchItem.Value;
- }
- return str;
- }
- public string SaveUrlPics(string strHTML)
- {
- 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],Server.MapPath("images")+"/"
- +preStr+imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/")+1));
- strHTML=strHTML.Replace(imgurlAry[i],"images/"
- +preStr+imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/")+1));
- }
- return strHTML;
- }
- catch(Exception ex)
- {
- return ex.Message;
- }
- }
- }
- }