最近在跟着教程写一些简单的项目的时候用到了kindEditor编辑器,在后台添加文章时,使用到了,下面就讲一下使用方法吧。
首先是替换,将文本框替换为编辑器,这里的实现比较简单:
KindEditor.ready(function (K) {
window.editor = K.create('#Article_Content', {
height: '500px',
uploadJson: '@Url.Action("Upload", "Attachment")',
fileManagerJson: '@Url.Action("FileManagerJson", "Attachment")',
allowFileManager: true,
formatUploadUrl: false
});
然后可以选择上传附件什么的,主要方法在Attachment/Upload中,其中_uploadConfg是将配置中的文件读取出来,这里把代码贴上来
public ActionResult Upload()
{
var _uploadConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~").GetSection("UploadConfig")
as CMSDemo.Models.Config.UploadConfig;
//文件的最大限制
int _maxSize = _uploadConfig.MaxSize;
//保存的路径
string _savePath;
//文件路径
string _filePath = "~/" + _uploadConfig.Path + "/";
//文件名
string _fileName;
//拓展名
string _fileExt;
//文件类型
string _dirName;
//允许上传的类型
Hashtable extTable = new Hashtable();
extTable.Add("image", _uploadConfig.ImageExt);
extTable.Add("flash", _uploadConfig.FileExt);
extTable.Add("media", _uploadConfig.MediaExt);
extTable.Add("file", _uploadConfig.FileExt);
//获取到要上传的文件
HttpPostedFileBase _postFile = Request.Files["imgFile"];
if (_postFile == null)
return Json(new { error = 1, message = "请选择文件" });
_fileName = _postFile.FileName;
_fileExt = Path.GetExtension(_fileName).ToLower();
_dirName = Request.QueryString["dir"];
if (string.IsNullOrEmpty(_dirName))
_dirName = "image";
if (!extTable.ContainsKey(_dirName))
return Json(new { error = 1, message = "目录类型不存在" });
if (_postFile.InputStream == null || _postFile.InputStream.Length > _maxSize)
return Json(new { error = 1, message = "文件大小超过限制" });
if (string.IsNullOrEmpty(_fileExt) || Array.IndexOf(((string)extTable[_dirName]).Split(','), _fileExt.Substring(1).ToLower()) == -1)
return Json(new { error = 1, message = "不允许上传此类型的文件。 \n只允许" + ((String)extTable[_dirName]) + "格式。" });
_filePath += _dirName + "/" + DateTime.Now.ToString("yyyy-MM") + "/";
_savePath = Server.MapPath(_filePath);
//检查上传目录
if (!Directory.Exists(_savePath)) Directory.CreateDirectory(_savePath);
string _newFileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + _fileExt;
_savePath += _newFileName;
_filePath += _newFileName;
//保存文件
_postFile.SaveAs(_savePath);
//保存数据库记录
AttachmentService.Add(new Attachment()
{
Extension = _fileExt.Substring(1),
FilePath = _filePath,
Owner = User.Identity.Name,
UploadDate = DateTime.Now,
Type = _dirName,
});
return Json(new { error = 0, url = Url.Content(_filePath) });
}
</pre><p>接着就是附件管理了,方法在Attachment/FileManageJson中,</p><p><pre name="code" class="javascript"> public ActionResult FileManagerJson(int? id ,string dir)
{
Models.AttachmentManagerViewModel _attachmentViewModel;
IQueryable<CMSDemo.Models.Attachment> _attachments;
//id为null,表示是modelid为null,此时查询数据库中没有跟模型对应起来的附件列表(已上传,但上传的文章,还未保存)
if (id == null)
_attachments = AttachmentService.FindList(null, User.Identity.Name, dir);
else
//id不为null,返回指定模型的id和id为null附件列表
_attachments = AttachmentService.FindList((int)id, User.Identity.Name, dir, true);
//初始化一个列表
var _attachmentList = new List<Models.AttachmentManagerViewModel>(_attachments.Count());
foreach(var _attachment in _attachments)
{
_attachmentViewModel = new Models.AttachmentManagerViewModel()
{
datetime = _attachment.UploadDate.ToString("yyyy-MM-dd-HH-mm-ss"),
filetype = _attachment.Extension,
has_file = false,
is_dir = false,
is_photo = _attachment.Type.ToLower() == "image" ? true : false,
filename = Url.Content(_attachment.FilePath),
// Filesize=0
};
FileInfo _fileInfo = new FileInfo(Server.MapPath(_attachment.FilePath));
_attachmentViewModel.filesize = (int)_fileInfo.Length;
_attachmentList.Add(_attachmentViewModel);
}
//_attachmentList.Count
return Json(new { moveup_dir_path = "", current_dir_path = "", current_url = "",
total_count = _attachmentList.Count, file_list = _attachmentList },JsonRequestBehavior.AllowGet);
}
其中AttachmentManagerViewModel的模型,是官方文档的模型,我修改过模型后不能正常使用了,所以不能随意修改
public class AttachmentManagerViewModel
{
public bool is_dir { set; get; }
public bool has_file { set; get; }
public int filesize { get; set; }
public bool is_photo { get; set; }
public string filetype { get; set; }
public string filename { get; set; }
public string datetime { get; set; }
}
最后就是创建对话框,来显示我们刚才上传的附件了,我这里的附件主要是图片
var editor2 = K.editor({
fileManagerJson: '@Url.Action("FileManagerJson", "Attachment")'
});
K('#btn_picselect').click(function () {
editor2.loadPlugin('filemanager', function () {
editor2.plugin.filemanagerDialog({
viewType: 'VIEW',
dirName: 'image',
clickFn: function (url, title) {
var url;
$.ajax({
type: "post",
url: "@Url.Action("CreateThumbnail", "Attachment")",
data: { originalPicture: url },
async: false,
success: function (data) {
if (data == null) alert("生成缩略图失败!");
else {
K('#DefaultPicUrl').val(data);
K('#imgpreview').attr("src", data);
}
editor2.hideDialog();
}
});
}
});
});
});
官方也有相应的上传附件的方法,需要的可以去官方查阅相关文档