自动上传编辑器中的远程图片与自动替换alt标签
#region 增加一条数据
/// <summary>
/// 增加一条数据
/// </summary>
public int Add( NewsEntity model )
{
//未添加图片说明的添加说明
MatchCollection matchs = Regex.Matches(model.Content, "<img.*/?>(<img/>)?", RegexOptions.IgnoreCase);
Match filePath;
foreach (Match match in matchs)
{
model.Content = model.Content.Replace(match.Value, match.Value.Replace("alt=\"\"", "alt=\"" + model.Title + "\""));
//将远程包含http和不是chinayq.com服务器中的图片上传
filePath = Regex.Match(match.Value, @"(http)+.*(jpg|png|gif|jpeg)", RegexOptions.IgnoreCase);
if (filePath.Success && filePath.Value.IndexOf("chinayq.com") < 0)
{
model.Content = model.Content.Replace(filePath.Value, WebUtility.PicOperate.UploadHttpFile(filePath.Value.Replace("\"", "")));
}
}
return dal.Add(model);
}
#endregion
/// <summary>
/// 上传远程文件到本地服务器
/// </summary>
/// <param name="filePath">远程文件</param>
/// <returns></returns>
public static string UploadHttpFile(string urlPath)
{
string filePath =string.Format("/upload/contentimg/{0}/",System.DateTime.Now.ToString("yyyyMMdd"));
string fileName=GenerateFileName()+Path.GetExtension(urlPath);
WebRequest request = WebRequest.Create(urlPath);
//使用默认验证
request.Credentials = CredentialCache.DefaultCredentials;
if (!Directory.Exists(serverPath + filePath)) { Directory.CreateDirectory(serverPath + filePath); }
string folderName =filePath + fileName;
System.Drawing.Image image = System.Drawing.Image.FromStream(request.GetResponse().GetResponseStream());
image.Save(serverPath+folderName);
image.Dispose();
return folderName;
}
注意:使用WebRequest 需要引用system.net空间
model.Content:FCK编辑器中的内容