kindeditor是一個很是好用的富文本編輯器,它的簡單使用我就再也不介紹了。 而kindeditor卻對圖片的處理不夠理想。html
本篇博文須要解決的問題有兩個:web
1.擴展粘貼圖片功能演示json
2.修改圖片上傳路徑演示:api
咱們的網站演示地址是:http://localhost:9393/安全
咱們的圖片服務器地址是:http://localhost:9394/服務器
咱們能夠看到圖片被直接上傳到了圖片服務器。同時咱們能夠配置圖片是上傳到本地仍是圖片服務器。app
1.粘貼圖片功能擴展async
具體請參考:http://www.cnblogs.com/cztisthebest/p/5913353.html編輯器
2.修改圖片上傳路徑並經過webapi上傳圖片到圖片服務器功能擴展分佈式
第一步:引用LitJSON.dll
由於我使用的開發語言是C#&ASP.NET MVC。因此首先須要在項目中引用LitJSON.dll,以下圖:
第二步:修改上傳文件:upload_json.ashx
<%@ WebHandler Language="C#" Class="Upload" %> /** * KindEditor ASP.NET * * 本ASP.NET程序是演示程序,建議不要直接在實際項目中使用。 * 若是您肯定直接使用本程序,使用以前請仔細確認相關安全設置。 * */ using System; using System.Collections; using System.Web; using System.IO; using System.Globalization; using LitJson; public class Upload : IHttpHandler { private HttpContext context; public void ProcessRequest(HttpContext context) { //定義容許上傳的文件擴展名 Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp"); extTable.Add("flash", "swf,flv"); extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //最大文件大小 int maxSize = 1000000; this.context = context; HttpPostedFile imgFile = context.Request.Files["imgFile"]; if (imgFile == null) { showError("請選擇文件。"); } //文件類型 String dirName = context.Request.QueryString["dir"]; if (String.IsNullOrEmpty(dirName)) { dirName = "image"; } if (!extTable.ContainsKey(dirName)) { showError("目錄名不正確。"); } String fileName = imgFile.FileName; String fileExt = Path.GetExtension(fileName).ToLower(); if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) { showError("上傳文件大小超過限制。"); } if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) { showError("上傳文件擴展名是不容許的擴展名。\n只容許" + ((String)extTable[dirName]) + "格式。"); } var saveDir = context.Request["saveDir"]; string saveDirStr = null; if (saveDir == null) { saveDirStr = "tmp"; } else { saveDirStr = saveDir.ToString(); } //是否分佈式上傳 bool isDFS = false; var dfs = context.Request["dfs"]; if (dfs != null && dfs.ToString() == "1") { isDFS = true; } Hashtable hash = new Hashtable(); if (isDFS) { var imageUrl = Cloud.Utility.ConfigHelper.Images_SITE_URL; var client = new RestSharp.RestClient(imageUrl);//TODO api基路徑 var request = new RestSharp.RestRequest("file/upload", RestSharp.Method.POST); request.AlwaysMultipartFormData = true; request.AddHeader("dir", dirName + "/" + saveDirStr); request.AddHeader("imageUrl", imageUrl); request.AddFile("file", Cloud.Utility.StreamHelper.ConvertToBytes(imgFile.InputStream), context.Server.HtmlEncode(imgFile.FileName)); var posttask = client.ExecutePostTaskAsync(request); if (posttask.Result.StatusCode == System.Net.HttpStatusCode.OK) { var url = posttask.Result.Content.Trim(new char[] { '[', ']', '"' }); hash["url"] = url; } else { showError("分佈式上傳失敗"); } } else { //文件保存目錄 string savePath = "/upload/kindeditor/" + dirName + "/" + saveDirStr; String dirPath = context.Server.MapPath(savePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } String newFileName = DateTime.Now.ToString("_yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; String filePath = dirPath + "/" + newFileName; imgFile.SaveAs(filePath); hash["url"] = savePath + "/" + newFileName; } hash["error"] = 0; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(JsonMapper.ToJson(hash)); context.Response.End(); } private void showError(string message) { Hashtable hash = new Hashtable(); hash["error"] = 1; hash["message"] = message; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(JsonMapper.ToJson(hash)); context.Response.End(); } public bool IsReusable { get { return true; } } }
客戶端傳過來一個文件保存目錄的參數:saveDir
客戶端傳過來一個是否上傳文件到圖片服務器的參數:dfs,若是dfs=1表明上傳到圖片服務器,不然上傳到本地
上傳文件的核心代碼:其中使用到了一個開源的上傳組件RestSharp
第三步:webapi圖片服務器端代碼:
[Route("file/upload")]
[HttpPost]
public async Task<HttpResponseMessage> PostFormData() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var dir = Request.Headers.GetValues("dir").First(); var imageUrl = Request.Headers.GetValues("imageUrl").First(); string root = System.Web.HttpContext.Current.Server.MapPath(Path.Combine("~/images/", dir)); if (System.IO.Directory.Exists(root) == false) { System.IO.Directory.CreateDirectory(root); } var provider = new MultipartFormDataStreamProvider(root); provider = new RenamingMultipartFormDataStreamProvider(root);//重命名寫法 await Request.Content.ReadAsMultipartAsync(provider); var urlList = new List<string>(); var url = ""; foreach (MultipartFileData file in provider.FileData) { string path = file.LocalFileName; var start = path.IndexOf("\\images"); path = path.Substring(start); var mainURL = imageUrl;// ConfigurationManager.AppSettings["MainImageURL"]; url = mainURL + path.Replace("\\", "/"); urlList.Add(url); //return Request.CreateResponse(HttpStatusCode.OK, url); } return Request.CreateResponse(HttpStatusCode.OK, urlList); }
其中文件重命名方法爲:
/// <summary>
/// 文件上傳並重命名
/// </summary>
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public string Root { get; set; } public RenamingMultipartFormDataStreamProvider(string root) : base(root) { Root = root; } public override string GetLocalFileName(HttpContentHeaders headers) { string filePath = headers.ContentDisposition.FileName; // Multipart requests with the file name seem to always include quotes. if (filePath.StartsWith(@"""") && filePath.EndsWith(@"""")) filePath = filePath.Substring(1, filePath.Length - 2); return Path.GetFileNameWithoutExtension(filePath)+ DateTime.Now.ToString("_yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + Path.GetExtension(filePath).ToLower(); return filePath; } }
第四步:kindeditor配置:
主要配置的是UploadJson參數:saveDir表明保存的目錄,dfs表明是否上傳到圖片服務器,若是dfs=1表明上傳到圖片服務器不然上傳到本地。