使用的是asp.net MVC 上傳圖片。javascript
1.下載Kindeditor的對應的包html
2.html頁面java
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>UploadByKindeditor</title> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Content/KindEditor/kindeditor.js"></script> <script src="~/Content/KindEditor/plugins/image/image.js"></script> <script type="text/javascript"> var editor; var options = { uploadJson: '/BusinessPublic/UploadImage', // (BusinessPublic,UploadImage爲Action,下同) 上傳圖片 fileManagerJson: '/BusinessPublic/UploadFile', //上傳文件 allowFileManager: true, width: "100%", //編輯器的寬度爲100% height: "250px", //編輯器的高度爲100px filterMode: false, //不會過濾HTML代碼 resizeMode: 1 //編輯器只能調整高度 }; $(function () { editor = KindEditor.create('#content', options); }); </script> </head> <body> <div> 內容:<textarea id="content" name="content" style="height:300px;"></textarea> </div> </body> </html>
3.後臺Action代碼: 使用post提交 (上傳文件都是使用post方式)jquery
[HttpPost] public ActionResult UploadImage() { string savePath = "/Resource/KindeditorImage/"; string fileTypes = "gif,jpg,jpeg,png,bmp"; int maxSize = 1000000; Hashtable hash = new Hashtable(); HttpPostedFileBase file = Request.Files["imgFile"]; if (file == null) { hash = new Hashtable(); hash["error"] = 0; hash["url"] = "請選擇文件"; return Json(hash); } string dirPath = Server.MapPath(savePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } string fileName = file.FileName; string fileExt = Path.GetExtension(fileName).ToLower(); ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(',')); if (file.InputStream == null || file.InputStream.Length > maxSize) { hash = new Hashtable(); hash["error"] = 0; hash["url"] = "上傳文件大小超過限制"; return Json(hash); } if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { hash = new Hashtable(); hash["error"] = 0; hash["url"] = "上傳文件擴展名是不容許的擴展名"; return Json(hash); } string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; string filePath = dirPath + newFileName; file.SaveAs(filePath); //圖片在服務器上的路徑 string fileUrl = savePath + newFileName; hash = new Hashtable(); hash["error"] = 0; hash["url"] = fileUrl; return Json(hash, "text/html;charset=UTF-8"); ; }
PS:服務器
(3)返回Json的信息:asp.net
//成功時 { "error" : 0, "url" : "http://www.example.com/path/to/file.ext" }
//失敗時 { "error" : 1, "message" : "錯誤信息" }
(2)編寫服務器端圖片上傳方法,要求返回的結果爲JSON格式編輯器