Oct 09, 2013, 1:37 PM
[CLOSED] how to replace img src with Regex
i want to replace img tag's src ,because the src is out of server, so i want to download the pic and save to server,
<ext:FieldContainer runat="server" LabelWidth="65" Margin="4" FieldLabel="图片下载">
<Items>
<ext:Button runat="server" Icon="DiskDownload" ID="btn_picdownload">
<DirectEvents>
<Click OnEvent="SavePics">
<EventMask ShowMask="True"></EventMask>
</Click>
</DirectEvents>
</ext:Button>
</Items>
</ext:FieldContainer>
<ext:HtmlEditor runat="server" ID="he_cont" AnchorHorizontal="100%" AnchorVertical="-78">
</ext:HtmlEditor>
protected void SavePics(object sender, DirectEventArgs e)
{
var editorContent = he_cont.Text;
Regex reg = new Regex(@"(?is)<img[^>]*?src=(['""\s]?)((?:(?!topics)[^'""\s])*)\1[^>]*?>"); //here is regex, could you please check it again? is it right?
foreach (Match m in reg.Matches(editorContent))
{
var url = m.Groups[2].Value; // here is the img's src value
var uploadedFile = new UploadedFile(url, "yyyy-MM-dd-HH-mm-ss");
var mywebclient = new WebClient();
try
{
mywebclient.DownloadFile(url, uploadedFile.PhysicalFilePath); //download the remote pic to my server.
}
catch (Exception ex)
{
X.Msg.Alert("消息", "下载失败");
}
var wp = uploadedFile.WebPath; //here is web path, i want to replace the url(the img's src value) with wp,
// then set the new editorContent to htmleditor's text
}
}
public class UploadedFile
{
public string WebPath;
public string PhysicalFilePath;
private readonly string _fileFormat;
private readonly string _fileName;
private string _newFileName;
private readonly string _y = System.DateTime.Now.Year.ToString(CultureInfo.InvariantCulture);
private readonly string _m = System.DateTime.Now.Month.ToString(CultureInfo.InvariantCulture);
public UploadedFile(string filename, string fileFormat)
{
this._fileName = filename;
this._fileFormat = fileFormat;
CreateNewFileName();
CreatePhysicalUploadedPath();
CreatePhysicalFilePath();
CreateWebPath();
}
private void CreateNewFileName()
{
var ran = new Random();
this._newFileName = DateTime.Now.ToString(@"yyyy-MM-dd-HH-mm-ss") + "-" + ran.Next(100, 999)
+ Path.GetExtension(this._fileName);
}
private void CreatePhysicalFilePath()
{
var ran = new Random();
string sNewName = DateTime.Now.ToString(this._fileFormat) + "-" + ran.Next(100, 999)
+ Path.GetExtension(this._fileName);
this.PhysicalFilePath = HttpContext.Current.Server.MapPath("/Uploads/" + _y + "/" + _m + "/" + sNewName);
}
private void CreateWebPath()
{
this.WebPath = "/Uploads/" + _y + "/" + _m + "/" + this._newFileName;
}
private void CreatePhysicalUploadedPath()
{
string pathMoth = HttpContext.Current.Server.MapPath("/Uploads/" + _y + "/" + _m);
if (!Directory.Exists(pathMoth))
{
Directory.CreateDirectory(pathMoth);
}
}
}
could you please help me?
Last edited by Daniil; Oct 15, 2013 at 6:44 AM.
Reason: [CLOSED]