HTML编辑器网络图片本地化

editor.html
+展开
-HTML
<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=gb2312" />
    <title>HTML编辑器网络图片本地化</title>
    <meta content="求思路 代码或案例 编辑器 图片自动本化 Web编辑器 HTML编辑器" name="Keywords"/>
    <meta content="编辑器的图文内容提交前(或者别的触发时间),自动将里面外链性质的图片转成本地图片。说白点就是自动下载外链图片到本地,再用本地图片的地址替换掉原地址。" name="description"/>
  </head>
  <body>
  图片网络路径:<input type="text" style="width:300px" id="txtURL" /><input type="button" value="插入到编辑器中" onclick="loadImg(this)" /><br >
  <iframe id="editor" style="width:500px;height:300px;border:solid 1px black;" marginheight="0" marginwidth="0" frameborder="0"></iframe>
  <script type="text/javascript">
  var win,doc;
  window.onload=function(){
    win=document.getElementById('editor').contentWindow;doc=win.document;
    doc.designMode='On';
  }
  function loadImg(btn){
    var txt=document.getElementById('txtURL'),url=txt.value;
    if(!/https?:\/\/[\s\S]+\.(jpg|bmp|png|gif)$/i.test(url)){
      alert('请输入正确的图片路径!');txt.select();return false;
    }
    var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("microsoft.xmlhttp");
    xhr.open('get','loadimg.ashx?u='+escape(url)+'&_dc='+new Date().getTime(),true);//注意使用的是动态页面捉取远程图片保存到本地服务器上
    xhr.onreadystatechange=function(){
      if(xhr.readyState==4){
        if(xhr.status==200){
          var o=eval('('+xhr.responseText+')');
          if(o.success){
             win.focus();
             doc.execCommand('InsertImage',false,'/local/'+o.fn);//由于返回的只是文件名,所以需要将路径 local加上,并且使用了绝对路径
          }
          else alert('发生错误:'+o.err);
        }
        else alert('动态页发生错误,请联系管理员!');
      }
    }
    xhr.send(null);
  }
  </script> 
  </body>
</html>


loadimg.ashx,捉取远程图片的动态页面
+展开
-C#
<%@ WebHandler Language="C#" Class="loadimg" %>

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
public class loadimg : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string u = context.Request.QueryString["u"], json = "";
        if (Regex.IsMatch(u, @"https?:\/\/[\s\S]+\.(jpg|bmp|png|gif)$", RegexOptions.IgnoreCase | RegexOptions.Compiled))//正则验证url是否正确
        {
            string fn = Guid.NewGuid().ToString() + Path.GetExtension(u);
            WebClient wc = new WebClient();
            try
            {//下载图片到网站根目录下的local文件夹里面
                wc.DownloadFile(u, context.Server.MapPath("~/local/" + fn));
                json = "{success:true,fn:'" + fn + "'}";
            }
            catch { json = "{success:false,err:'下载图片失败!'}"; }
            wc.Dispose();
        }
        else json = "{success:false,err:'请输入正确的图片路径!'}";
        context.Response.Charset = "gb2312";
        context.Response.Write(json);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

加支付宝好友偷能量挖...


原创文章,转载请注明出处:HTML编辑器网络图片本地化

评论(0)Web开发网
阅读(197)喜欢(0)JavaScript/Ajax开发技巧