在使用Tinymce的过程中需要用到图片上传功能,而提供的上传插件在上传文件后是给了一个连接地址,就想用户需要什么图片,不能用最直观的方式表现出来么!
虽然官网上也有一个文件管理的插件moxiemanager,可奈何他是收费的!https://www.tiny.cloud/docs/plugins/moxiemanager/
然后就打算自己弄一个,其实实现效果起来很简单,就只是做了一个类型相册管理的功能,然后在点击图片的时候,将图片的地址信息插入到编辑器里就行了,由于后台用的是layui
的框架,所以界面也就用了layui来实现,这里我只弄了上传,删除功能,也可自己添加检索等功能,实现效果如下
1 、添加插件
我们需要在tinymce的 Plugins 目录下新建一个filemanager文件夹,并添加一个名为plugin.min.js ,其中editor传参后再图片管理页面通过
var editor = top.tinymce.activeEditor.windowManager.getParams().editor; 获取编辑器对象,进行图片插入操作
tinymce.PluginManager.add("filemanager", function (editor, url) {
editor.addButton("filemanager", {
title: "图片管理",
icon: 'image',
onclick: function () {
editor.windowManager.open({
title: "图片管理",
url: "/Administrator/Filemanager/Editor",
width: window.innerWidth * 0.9,
height: window.innerHeight * 0.8
}, {
editor: editor // pointer to access editor from cshtml
})
}
})
});
2. 相册功能实现
文件夹管理实体类
public class FileManagerDirectoryEntity : BaseEntity
{
///
/// 父级Id
///
public int ParentId { get; set; }
///
/// 文件夹名称
///
public string Name { get; set; }
///
/// 路径
///
public string FullPath { get; set; }
///
/// 子文件数量
///
public int ChildrenCount { get; set; }
}
文件管理实体类
public class FileManagerDirectoryEntity : BaseEntity
{
///
/// 父级Id
///
public int ParentId { get; set; }
///
/// 文件夹名称
///
public string Name { get; set; }
///
/// 路径
///
public string FullPath { get; set; }
///
/// 子文件数量
///
public int ChildrenCount { get; set; }
}
相册功能具体实现controller
public class FileManagerController : Controller
{
#region Core
private readonly IRepository _fileManagerDirectoryRepository;
private readonly IRepository _fileManagerFilesRepository;
private const string smallImage = "_small";
public FileManagerController(
IRepository fileManagerDirectoryRepository,
IRepository fileManagerFilesRepository
)
{
this._fileManagerDirectoryRepository = fileManagerDirectoryRepository;
this._fileManagerFilesRepository = fileManagerFilesRepository;
}
#endregion
///
/// 编辑器插件
/// 获取文件数据
///
///
///
public ActionResult Editor(int dirId = 0) {
List modelList = new List();
//加载该文件夹下的文件夹
var dirList = _fileManagerDirectoryRepository.Table
.Where(x=>x.ParentId==dirId)
.OrderByDescending(x=>x.CreateTime)
.ToList();
foreach(var item in dirList)
{
FileManagerFileModel model = new FileManagerFileModel();
model.Id = item.Id;
model.Name = item.Name;
model.FullPath = item.FullPath;
model.FileType = 2;
model.ChildrenCount = item.ChildrenCount;
modelList.Add(model);
}
//加载该文件夹下的图片文件
var fileList = _fileManagerFilesRepository.Table
.Where(x => x.DirectoryId == dirId)
.OrderByDescending(x => x.CreateTime)
.ToList();
foreach (var item in fileList)
{
FileManagerFileModel model = new FileManagerFileModel();
model.Id = item.Id;
model.Name = item.Name;
model.FullPath = item.FullPath;
model.SmallFullPath = item.FullPath + smallImage + item.FileExt;
model.FileType = 1;
modelList.Add(model);
}
return View(modelList);
}
///
/// 创建文件夹
///
///
///
public ActionResult _AddDirectory(int dirId) {
return View();
}
///
/// 文件夹信息保存
///
///
///
///
public ActionResult _AddDirectorySave(int dirId , string dirName) {
var parentDirEntity = _fileManagerDirectoryRepository.GetById(dirId);
if (!string.IsNullOrEmpty(dirName))
{
var parentDirPath = parentDirEntity == null ? "/Content/FileManager/" : parentDirEntity.FullPath;
if(parentDirEntity != null)
{
parentDirEntity.ChildrenCount++;
}
FileManagerDirectoryEntity entity = new FileManagerDirectoryEntity();
entity.ParentId = dirId;
entity.Name = dirName;
entity.FullPath = string.Format("{0}/{1}/", parentDirPath, Guid.NewGuid());
if (!Directory.Exists(Server.MapPath(entity.FullPath)))
{
Directory.CreateDirectory(Server.MapPath(entity.FullPath));
}
_fileManagerDirectoryRepository.Insert(entity);
_fileManagerDirectoryRepository.SaveChanges();
}
return RedirectToAction("Editor",new { dirId = dirId});
}
///
/// 上传图片
///
///
///
public JsonResult UploadImage(int dirId)
{
//路径地址
string fileUrl = "";
var parentDirEntity = _fileManagerDirectoryRepository.GetById(dirId);
var parentDirPath = parentDirEntity == null ? "/Content/FileManager/" : parentDirEntity.FullPath;
HttpFileCollectionBase postfile = HttpContext.Request.Files;
if (postfile == null)
{
return Json(new { code = 1, msg = "文件不能为空" });
}
var file = postfile[0];
string extName = Path.GetExtension(file.FileName);
using (System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream))
{
string fileName = Guid.NewGuid().ToString() + extName;
string smallImgName = string.Format("{0}{1}{2}", fileName, smallImage, extName);
string route = Server.MapPath(parentDirPath);
fileUrl = Path.Combine(parentDirPath, fileName);
string savePath = Path.Combine(route, fileName);
//缩略图路径
string smallImgPath = Path.Combine(route, smallImgName);
//生成缩略图
try
{
ImageResizer.Fit(image, 160, 160, ImageResizeMode.Crop, ImageResizeScale.Down).Save(smallImgPath);
}
catch (Exception)
{
return Json(new { flag = false, msg = "生成缩略图出错!" });
}
file.SaveAs(savePath);
}
#region 添加数据到素材表
FileManagerFilesEntity entity = new FileManagerFilesEntity();
entity.FileExt = extName;
entity.FullPath = fileUrl;
entity.Name = Path.GetFileNameWithoutExtension(file.FileName);
entity.DirectoryId = dirId;
entity.Size = file.ContentLength;
_fileManagerFilesRepository.Insert(entity);
_fileManagerFilesRepository.SaveChanges();
#endregion
if (parentDirEntity != null)
{
parentDirEntity.ChildrenCount++;
}
_fileManagerDirectoryRepository.SaveChanges();
return Json(new { code = 0 });
}
public class DeleteFilesParams
{
public int Id { get; set; }
public int Type { get; set; }
}
///
/// 删除选中文件夹及图片
///
///
public JsonResult CheckedFilesDelete(List checkeds)
{
var directoryList = _fileManagerDirectoryRepository.Table.ToList();
var fileList = _fileManagerFilesRepository.Table.ToList();
foreach(var item in checkeds)
{
//删除图片
if (item.Type == 1)
{
var fileEntity = fileList.FirstOrDefault(x => x.Id == item.Id);
string path = Server.MapPath(fileEntity.FullPath);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
var parentDir = directoryList.Find(x => x.Id == fileEntity.DirectoryId);
if (parentDir != null)
{
parentDir.ChildrenCount--;
}
_fileManagerFilesRepository.Delete(fileEntity);
}
else
{
var dirEntity = directoryList.FirstOrDefault(x => x.Id == item.Id);
DeleteChildDirFiles(dirEntity.Id, directoryList, fileList);
string path = Server.MapPath(dirEntity.FullPath);
if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
var parentDir = directoryList.Find(x => x.Id == dirEntity.ParentId);
if (parentDir != null)
{
parentDir.ChildrenCount--;
}
_fileManagerDirectoryRepository.Delete(dirEntity);
}
}
_fileManagerFilesRepository.SaveChanges();
_fileManagerDirectoryRepository.SaveChanges();
return Json(new { code = 0 });
}
public void DeleteChildDirFiles(int pid,List dirList, List files) {
var dirEntityList = dirList.Where(x => x.ParentId == pid);
var fileEntityList = files.Where(x => x.DirectoryId == pid);
foreach (var item in dirEntityList)
{
DeleteChildDirFiles(item.Id, dirList, files);
_fileManagerDirectoryRepository.Delete(item);
}
foreach (var item in fileEntityList)
{
_fileManagerFilesRepository.Delete(item);
}
_fileManagerDirectoryRepository.SaveChanges();
_fileManagerFilesRepository.SaveChanges();
}
}
文件管理页面 Editor.chtml
@using Web.Areas.Administrator.Models
@model List
@{
Layout = null;
}
文件管理
@if (!string.IsNullOrWhiteSpace(Request["dirId"]))
{
-
...
}
@if (Model.Any())
{
foreach (var item in Model)
{
-
@if (item.FileType == 1)
{
}
else
{
}
}
}
新增文件夹页面 _AddDirectory.chtml
@{
Layout = null;
}
3. 将选中图片插入编辑器
在图片列表的页面中,我们只需要在点击图片的事件中调用Tinymce编辑器的插入方法即可,以下为插入图片的代码