您的位置:首页 > 编程语言 > ASP

获取远端图片到本地服务器--asp.net实现

2012-03-21 11:22 232 查看
static public string ReplaceRemoteUrl(string strContent)

{

string resultStr=strContent;

string SaveFilePath = "/images/upload/";

if (SaveFilePath.Substring(SaveFilePath.Length-1,1) !="/")

{

SaveFilePath =SaveFilePath +"/";

}

string regex = "((http|https|ftp|rtsp|mms):(//////|////////){1}((//w)+[.]){1,}(net|com|cn|org|cc|tv|[0-9" +

"]{1,3})({1}(gif|jpg|png|bmp]//S*///)((//S)+[.]{1}(gif|jpg|png|bmp)))";

System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.ExplicitCapture | System.Text.RegularExpressions.RegexOptions.Multiline)

| System.Text.RegularExpressions.RegexOptions.IgnoreCase);

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

System.Text.RegularExpressions.MatchCollection RemoteFileMc = reg.Matches(strContent);

foreach(Match RemoteFileurl in RemoteFileMc)

{

string RemoteFile =RemoteFileurl.ToString();

string webHost=System.Web.HttpContext.Current.Request.ServerVariables["Server_Name"];

if (RemoteFile.IndexOf(webHost)>0)

{

continue;

}

else

{

string[] arrSaveFileName= RemoteFile.Split('.');

string SaveFileType = arrSaveFileName[arrSaveFileName.Length-1];

System.Random rd=new Random(100);

string ranNum =rd.Next(1000).ToString();

string SaveFileName = SaveFilePath+ System.DateTime.Now.ToFileTimeUtc() + ranNum+"."+SaveFileType;

string SaveFileNameFull= System.Web.HttpContext.Current.Request.ApplicationPath +SaveFileName;

SaveRemoteFile(SaveFileNameFull, RemoteFile);

resultStr = strContent.Replace(RemoteFile, SaveFileNameFull);

}

}

return resultStr;

}

static private void SaveRemoteFile(string LocalFileName, string RemoteFileUrl)

{

WebClient wb=new WebClient();

string PhysicalLocalFileName = System.Web.HttpContext.Current.Server.MapPath(LocalFileName);

wb.DownloadFile(RemoteFileUrl, PhysicalLocalFileName);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: