C# MVC 使用 CKEditor图片上传 提示“不正确的服务器响应”

重点:看一下你使用的CKEditor版本

过程:

后台需要一款富文本编辑器。经过挑选后,最后选择了FCKEditor 的升级版 CKEditor 。在官网下载了4.10.1版本。

经过一番配置后,富文本可以正常显示。在上传图片的时候,出现了问题。一直提示我“不正确的服务器响应”。经过一番搜索发现配置和网上给出的配置都是一样的,却总还是错误。

 

后来发现一篇说新版本的CKEditor上传图片的返回值修改了。经过一番摸索,终于解决问题。

上图:

 

原来之前的版本使用的通过 script 控制的tab跳转并填入图片地址的方式新版本已经弃用,改用新的Json 的方式传递。下面贴上配置和后端代码:

 

CKEditor config.js配置

 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方法 

        [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" })

 

posted @ 2018-10-04 22:24  leoxuan  阅读(988)  评论(0编辑  收藏  举报