三步在mvc中使用KindEditor开发富文本编辑器上传图片功能

  一.在你的项目中加入KindEditor的js包,再在你的view视力中加入js文件的引用

  <script charset="utf-8" src="@Url.Content("~/Areas/FXGHDA/Components/kindeditor-4.1.10/kindeditor.js")"></script>
  <script charset="utf-8" src="@Url.Content("~/Areas/FXGHDA/Components/kindeditor-4.1.10/lang/zh_CN.js")"></script>

  二.创建KindEditor对象,并设置上传图片的Action地址

 var editor;
 KindEditor.ready(function (K) {
                editor = K.create('#editor_id', {
                    width: '700px',
                    heigth: '450px',
                    uploadJson: '/FXGHDA/KindEdit/UploadImage'
                });
            });

  三.编写UploadImage后台方法

    string uploadFilePath = System.Configuration.ConfigurationSettings.AppSettings["News"];

        [HttpPost]
        public JsonResult UploadImage(FormCollection form)
        {
            //定义消息
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["url"] = "";
            if (Request.Files.Count != 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                //最大文件大小
                int maxSize = 10000000;
                //文件名
                String fileName = file.FileName;
                //文件格式
                String fileExt = Path.GetExtension(fileName).ToLower();
                //定义允许上传的文件扩展名
                string[] extArr = new[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
                if (file.InputStream == null || file.InputStream.Length > maxSize)
                {
                    hash["error"] = 1;
                    hash["message"] = "上传文件大小超过限制!";
                }
                else if (String.IsNullOrEmpty(fileExt) || !extArr.Contains(fileExt))
                {
                    hash["error"] = 1;
                    hash["message"] = "上传文件扩展名是不允许的扩展名!";
                }
                else
                {
                    String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
                    string path = Server.MapPath(uploadFilePath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    String fileUrl = Path.Combine(path, newFileName);
                    file.SaveAs(fileUrl);
                    hash["error"] = 0;
                    hash["url"] = Path.Combine(uploadFilePath, newFileName);
                }
            }
            else
            {
                hash["error"] = 1;
                hash["message"] = "请选择文件!";
            }
            return Json(hash, "text/html;charset=UTF-8");
        }

要注意的几个地方:

1.返回的Json格式要指定为"text/html;charset=UTF-8",否则在IE下会弹出下载窗口

2.在查看视图的时候,一定要在你的图片路径字段前调用@Html.Raw(Model.picPath),否则页面上输出的是你保存在数据库的路径字符串,而不会解析成Html代码,也就看不到你上传的图片了

最后来看一下效果吧!

 

posted @ 2014-03-31 17:13  o漆黑之牙o  阅读(1097)  评论(0编辑  收藏  举报