經過幾天的資料收集,終於完成了該編輯器的圖片上傳,視頻插入功能,視頻插入功能主要借用了該編輯器的插入iframe功能,如原始插件圖:
修改后的插件圖如下(其中我隱藏掉了一些不需要使用的插件功能):
配置編輯器
打開ueditor.config.js,我修改后的代碼片段如下:
//工具欄上的所有的功能按鈕和下拉框,可以在new編輯器的實例時選擇自己需要的從新定義 , toolbars: [[ 'fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'directionalityltr', 'directionalityrtl', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload', 'emotion', 'insertvideo', 'map', 'insertframe', 'pagebreak', 'template', 'background', '|', 'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|', 'searchreplace', 'help', 'drafts' ]] //當鼠標放在工具欄上時顯示的tooltip提示,留空支持自動多語言配置,否則以配置值為准 ,labelMap:{ 'anchor': '', 'undo': '', 'insertframe': '插入微信視頻(只能插入v.qq.com騰訊視頻MP4格式', 'insertvideo': '插入普通視頻(適用於網站PC端)', 'simpleupload': '插入圖片(適用於網站PC端)' } ,initialFrameWidth:560 //初始化編輯器寬度,默認560 ,initialFrameHeight:300 //初始化編輯器高度,默認300
'insertframe': '插入微信視頻(只能插入v.qq.com騰訊視頻MP4格式',就是修改后的插入微信視頻功能(等下再講解)
首先來介紹下,上傳圖片的功能,微信因為開啟圖片防盜鏈功能,所以說直接上傳圖片功能返回的地址不能為本項目域名下的圖片路徑了,必須先上傳至微信服務器后,返回圖片的URL然后顯示在富文本中,點擊單圖片上傳功能按鈕后,選擇圖片后的處理方法修改如下:
在調用控件的頁面加載時
$(document).ready(function () { var ue = UE.getEditor('tbContent'); //重寫UEDITOR的getActionUrl 方法,定義自己的Action,上傳圖片保存至相應的位置 UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl; UE.Editor.prototype.getActionUrl = function (action) { if (action == 'uploadimage' || action == 'uploadfile') { var id = $('#carInfoId').val(); return '/UpLoadWeiXinImgHander.ashx'; } else { return this._bkGetActionUrl.call(this, action); } }; });
UpLoadWeiXinImgHander.ashx的事件方法如下:
/// <summary> /// UpLoadWeiXinImgHander 的摘要說明 /// </summary> public class UpLoadWeiXinImgHander : IHttpHandler { public void ProcessRequest(HttpContext context) { ///'遍歷File表單元素 HttpFileCollection files = HttpContext.Current.Request.Files; for (int iFile = 0; iFile < files.Count; iFile++) { // ///'檢查文件擴展名字 HttpPostedFile postedFile = files[iFile]; //HttpPostedFile postedFile = files[0]; string fileName; //, fileExtension fileName = System.IO.Path.GetFileName(postedFile.FileName); string fileContentType = postedFile.ContentType.ToString(); if (fileContentType == "image/gif" || fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg" || fileContentType == "image/pjpeg") { if (postedFile.ContentLength <= 2097152) { string filepath = postedFile.FileName; //得到的是文件的完整路徑,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName; //得到上傳的文件名20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = context.Server.MapPath("~/WeiXinImg/") + fileName;//取得文件在服務器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg //保存到本地文件夾 postedFile.SaveAs(serverpath);//上傳圖片到服務器指定地址 ////context.Request.Url.Authority.ToString()獲取當前主機頭或IP地址+端口號 //string imageurlpath = "http://" + context.Request.Url.Authority.ToString() + "/WeiXinImg/" + fileName; //上傳圖片素材至微信服務器獲取圖片Url WeiXinServer wxs = new WeiXinServer(); ///從緩存讀取accesstoken string Access_token = context.Cache["Access_token"] as string; if (Access_token == null) { //如果為空,重新獲取 Access_token = wxs.GetAccessToken(); //設置緩存的數據7000秒后過期 context.Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration); } string Access_tokento = Access_token.Substring(17, Access_token.Length - 37); string url = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}&type={1}", Access_tokento, "image"); string res = HttpUploadFile(url, serverpath); //判斷res結果集里面是否包含media_id if (res.Contains("url")) { //如果能進行到這里,那說明圖片已經上傳至微信服務器,是永久素材哦, //開始解析json串,使用前需要引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(res); string state = "SUCCESS"; //返回上傳信息 context.Response.Write("{'url':'" + jsonObj["url"].ToString() + "','title':'" + filename + "','state':'" + state + "'}"); } } else { context.Response.Write("<script>alert('上傳文件不能大於2M!')</script>"); } } else { context.Response.Write("<script>alert('只支持GIF、JPG、PNG格式的圖片!')</script>"); } } } public bool IsReusable { get { return false; } } /// <summary> /// Http上傳文件 /// </summary> public static string HttpUploadFile(string url, string path) { // 設置參數 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = path.LastIndexOf("\\"); string fileName = path.Substring(pos + 1); //請求頭部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.GetRequestStream(); postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(bArr, 0, bArr.Length); postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close(); //發送請求並獲取相應回應數據 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標網頁發送Post請求 Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream, Encoding.UTF8); //返回結果網頁(html)代碼 string content = sr.ReadToEnd(); return content; } }
這樣就實現了圖片的上傳功能,圖片的地址為微信服務器返回的URL地址;如果提示”此圖片來自微信公眾平台 未經允許不可引用”,其實很簡單,換用IE8以上的瀏覽器試試或谷歌瀏覽器就可以看到了。
好了,現在來介紹下,插入適用於微信中的視頻,微信規定(只能插入v.qq.com騰訊視頻MP4格式),那么先替換原有按鈕iframe得圖標為微信圖標,
1.打開themes文件夾下default下的images文件夾找到icons.png圖片把它拷出來放到電腦上,找個合成工具(我用的是美圖秀秀)把准備好的微信圖標圖片合成到該圖片中,合成后的效果圖如下:
以為合成之后,再把圖片覆蓋回去就可以了嗎?NONONO,還得修改樣式表才能達到效果,打開themes文件夾下default下的css文件下的ueditor.css
輸入查詢edui-for-insertframe,跳到該處根據圖片位置(原有應該是-240px -40px)實際修改圖片的定位就可以了哦。
/*插入微信視頻樣式*/
.edui-default .edui-for-insertframe .edui-icon {
background-position: -753px -78px;
}
測試一下是不是可以插入顯示了呢?至於騰訊視頻的上傳,要到騰訊視頻的官網注冊個賬戶或者用QQ登錄你自己的賬戶即可,上傳完MP4格式的視頻后,把視頻的地址復制到
地址欄里,然后設置寬度和高度就可以了哦。