標籤:lang code fine 使用 mic soft lin otp creat
最近在玩 asp.net core,不想用UEditor,想使用CKEditor。故需要圖片上傳功能。
廢話不多說,先上:
CKEditor 前端代碼:
<text id="content" name="content"></text> <script> CKEDITOR.replace(‘content‘); </script>
CKeditor config.js 配置代碼:需要配置圖片上傳路徑
CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = ‘fr‘; // config.uiColor = ‘#AADC6E‘; config.baseHref = "http://" + location.host; config.filebrowserImageUploadUrl = ‘/Upload/UploadImage‘; config.font_names = ‘宋體/宋體;黑體/黑體;楷體/楷體;幼圓/幼圓;微軟雅黑/微軟雅黑;‘ + config.font_names; config.allowedContent = true;};
如上代碼,我們使用UploadController的UploadImage方法來處理上傳事件。
服務端代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Hosting;using System.IO;using Ratuo.Common;namespace Ratuo.Web.Controllers{ public class UploadController : Controller { private IHostingEnvironment _env; public UploadController(IHostingEnvironment env) { _env = env; } public async Task<IActionResult> UploadImage() { string callback = Request.Query["CKEditorFuncNum"];//要求傳回值 var upload = Request.Form.Files[0]; string tpl = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(\"{1}\", \"{0}\", \"{2}\");</script>"; if (upload == null) return Content(string.Format(tpl, "", callback, "請選擇一張圖片!"), "text/html"); //判斷是否是圖片類型 List<string> imgtypelist = new List<string> { "image/pjpeg", "image/png", "image/x-png", "image/gif", "image/bmp" }; if(imgtypelist.FindIndex(x=>x == upload.ContentType) == -1) { return Content(string.Format(tpl, "", callback, "請上傳一張圖片!"), "text/html"); } var data = Request.Form.Files["upload"]; string filepath = _env.WebRootPath+"\\userfile\\images"; string imgname = Utils.GetOrderNum() + Utils.GetFileExtName(upload.FileName); string fullpath = Path.Combine(filepath, imgname); try { if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath); if (data != null) { await Task.Run(() => { using (FileStream fs = new FileStream(fullpath, FileMode.Create)) { data.CopyTo(fs); } }); } } catch (Exception ex) { return Content(string.Format(tpl, "", callback, "圖片上傳失敗:"+ ex.Message), "text/html"); } return Content(string.Format(tpl, "/userfile/images/" + imgname, callback, ""), "text/html"); } }}
編譯,預覽一下。即可!
.net core CKEditor 圖片上傳