C# MVC 使用 CKEditor圖片上傳 提示「不正確的服務器響應」

重點:看一下你使用的CKEditor版本前端

過程:後端

後臺須要一款富文本編輯器。通過挑選後,最後選擇了FCKEditor 的升級版 CKEditor 。在官網下載了4.10.1版本。服務器

通過一番配置後,富文本能夠正常顯示。在上傳圖片的時候,出現了問題。一直提示我「不正確的服務器響應」。通過一番搜索發現配置和網上給出的配置都是同樣的,卻總仍是錯誤。編輯器

 

後來發現一篇說新版本的CKEditor上傳圖片的返回值修改了。通過一番摸索,終於解決問題。url

上圖:spa

 

原來以前的版本使用的經過 script 控制的tab跳轉並填入圖片地址的方式新版本已經棄用,改用新的Json 的方式傳遞。下面貼上配置和後端代碼:code

 

CKEditor config.js配置orm

 1     //上傳圖片的方法
 2     config.filebrowserImageUploadUrl = "/Home/Upload";
 3 
 4     //圖片默認顯示文字爲空
 5     config.image_previewText = ' ';
 6 
 7     //設置語言
 8     config.language = 'zh-cn';
 9 
10     // 解決CKEditor圖片寬度自適應的問題 p img {    width: auto;    height: auto;    max - width: 100 %;}
11     config.disallowedContent = 'img{width,height};img[width,height]';

 

後端Upload方法 blog

        [HttpPost]
        public JsonResult Upload(HttpPostedFileBase upload)
        {
            string savePath = "/upload/";
            string dirPath = Server.MapPath(savePath);

            //若是目錄不存在則建立目錄
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);

            //獲取圖片文件名及擴展名
            var fileName = Path.GetFileName(upload.FileName);
            string fileExt = Path.GetExtension(fileName).ToLower();

            //用時間來生成新文件名並保存
            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            upload.SaveAs(dirPath + "/" + newFileName);

            //上傳成功後,咱們還須要返回Json格式的響應
            return Json(new
            {
                uploaded = 1,
                fileName = newFileName,
                url = savePath + newFileName
            });
        }    

 

前端調用圖片

//引入js文件
<
script src="~/Content/ckeditor/ckeditor.js"></script> <script src="~/Content/ckeditor/config.js"></script> //ckditor容器 @Html.TextAreaFor(model => model.ContentInfo, new { @class = "ckeditor" })
相關文章
相關標籤/搜索