【Kindeditor编辑器】 文件上传、空间管理

包括图片上传、文件上传、Flash上传、多媒体上传、空间管理(图片空间、文件空间等等)

一、编辑器相关参数

二、简单的封装类

这里只是做了简单的封装,欢迎大家指点改正。

public class KindeditorHelper
{
    /// <summary>
    /// 上传
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    public static ResponseUploadMessage Upload(RequestUploadMessage req)
    {
        if (req.imgFile == null || req.imgFile.ContentLength <= 0)
        {
            return new ResponseUploadMessage() { error = 1, message = "上传文件不能为空" };
        }

        if (req.dir == UploadFileType.image && req.imgFile.ContentType.IndexOf("image/") == -1)
        {
            return new ResponseUploadMessage() { error = 1, message = "上传图片格式错误" };
        }

        if (String.IsNullOrEmpty(req.savePath))
        {
            return new ResponseUploadMessage() { error = 1, message = "保存文件夹不能为空" };
        }

        //保存文件夹不存在就创建
        if (Directory.Exists(req.savePath) == false)
        {
            Directory.CreateDirectory(req.savePath);
        }

        string fileExtensions = Path.GetExtension(req.imgFile.FileName);
        string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssss") + new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999) + fileExtensions;

        string fullPath = Path.Combine(req.savePath, newFileName);
        req.imgFile.SaveAs(fullPath);

        return new ResponseUploadMessage() { error = 0, url = req.webUrl + newFileName };
    }

    /// <summary>
    /// 空间管理
    /// </summary>
    /// <param name="req"></param>
    /// <returns></returns>
    public static ResponseManageMessage Manage(RequestManageMessage req)
    {
        string[] fileTypes = new string[] { "gif", "jpg", "jpeg", "png", "bmp" };   //图片后缀名
        string currentPath = "";    //当前文件路径
        string currentUrl = "";     //当前URL路径
        string currentDirPath = ""; //当前文件夹路径
        string moveupDirPath = "";  //上一级文件夹路径

        string dirPath = req.savePath;
        string webUrl = req.webUrl;
        string path = req.path;

        if (String.IsNullOrEmpty(path))
        {
            path = "";
        }

        if (Directory.Exists(dirPath) == false)
        {
            Directory.CreateDirectory(dirPath);  //保存文件夹不存在就创建
        }

        if (path == "")
        {
            currentPath = dirPath;
            currentUrl = webUrl;
            currentDirPath = "";
            moveupDirPath = "";
        }
        else
        {
            currentPath = dirPath + path;
            currentUrl = webUrl + path;
            currentDirPath = path;
            moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
        }

        //不允许使用..移动到上一级目录
        if (Regex.IsMatch(path, @"\.\."))
        {
            HttpContext.Current.Response.Write("Access is not allowed.");
            HttpContext.Current.Response.End();
        }

        //最后一个字符不是/
        if (path != "" && !path.EndsWith("/"))
        {
            HttpContext.Current.Response.Write("Parameter is not valid.");
            HttpContext.Current.Response.End();

        }

        //目录不存在或不是目录
        if (Directory.Exists(currentPath) == false)
        {
            HttpContext.Current.Response.Write("Directory does not exist.");
            HttpContext.Current.Response.End();
        }

        string[] dirList = Directory.GetDirectories(currentPath);
        string[] fileList = Directory.GetFiles(currentPath);

        switch (req.order)
        {
            case "SIZE":
                Array.Sort(dirList, new NameSorter());
                Array.Sort(fileList, new SizeSorter());
                break;
            case "TYPE":
                Array.Sort(dirList, new NameSorter());
                Array.Sort(fileList, new TypeSorter());
                break;
            case "NAME":
                Array.Sort(dirList, new NameSorter());
                Array.Sort(fileList, new NameSorter());
                break;
            case "TIME":
                Array.Sort(dirList, new TimeSorter());
                Array.Sort(fileList, new TimeSorter());
                break;
        }

        ResponseManageMessage res = new ResponseManageMessage();
        res.moveup_dir_path = moveupDirPath;
        res.current_dir_path = currentDirPath;
        res.current_url = currentUrl;
        res.total_count = dirList.Length + fileList.Length;

        for (int i = 0; i < dirList.Length; i++)
        {
            DirectoryInfo dir1 = new DirectoryInfo(dirList[i]);
            FileList theDir = new FileList();
            theDir.is_dir = true;
            theDir.has_file = (dir1.GetFileSystemInfos().Length > 0);
            theDir.filesize = 0;
            theDir.is_photo = false;
            theDir.filetype = "";
            theDir.filename = dir1.Name;
            theDir.datetime = dir1.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
            res.file_list.Add(theDir);
        }

        for (int i = 0; i < fileList.Length; i++)
        {
            FileInfo file = new FileInfo(fileList[i]);
            FileList theFile = new FileList();
            theFile.is_dir = false;
            theFile.has_file = false;
            theFile.filesize = file.Length;
            theFile.is_photo = Array.IndexOf(fileTypes, file.Extension.Substring(1).ToLower()) >= 0;
            theFile.filetype = file.Extension.Substring(1);
            theFile.filename = file.Name;
            theFile.datetime = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
            res.file_list.Add(theFile);
        }

        return res;
    }
}

 RequestUploadMessage类

/// <summary>
/// 上传请求类
/// </summary>
public class RequestUploadMessage
{
    /// <summary>
    /// 类型
    /// </summary>
    public UploadFileType dir { get; set; }

    /// <summary>
    /// 本地地址
    /// </summary>
    public string localUrl { get; set; }

    /// <summary>
    /// 上传文件
    /// </summary>
    public HttpPostedFileBase imgFile { get; set; }

    /// <summary>
    /// 保存文件夹路径
    /// </summary>
    public string savePath { get; set; }

    /// <summary>
    /// Url地址
    /// </summary>
    public string webUrl { get; set; }
}

ResponseUploadMessage类

/// <summary>
/// 上传结果类
/// </summary>
public class ResponseUploadMessage
{
    /// <summary>
    /// 结果码 0成功 1失败
    /// </summary>
    public int error { get; set; }

    /// <summary>
    /// 信息
    /// </summary>
    public string message { get; set; }

    /// <summary>
    /// Url地址
    /// </summary>
    public string url { get; set; }
}

 RequestManageMessage类

/// <summary>
/// 空间管理类
/// </summary>
public class RequestManageMessage
{
    /// <summary>
    /// 类型
    /// </summary>
    public UploadFileType dir { get; set; }

    /// <summary>
    /// 排序
    /// </summary>
    public string order { get; set; }

    /// <summary>
    /// 路径
    /// </summary>
    public string path { get; set; }

    /// <summary>
    /// 文件夹路径 物理路径
    /// </summary>
    public string savePath { get; set; }

    /// <summary>
    /// URL
    /// </summary>
    public string webUrl { get; set; }
}

ResponseManageMessage类

public class ResponseManageMessage
{
    /// <summary>
    /// 上一级文件夹路径
    /// </summary>
    public string moveup_dir_path { get; set; }

    /// <summary>
    /// 当前文件夹路径
    /// </summary>
    public string current_dir_path { get; set; }

    /// <summary>
    /// 当前URL地址
    /// </summary>
    public string current_url { get; set; }

    /// <summary>
    /// 总数量 包括文件夹、文件
    /// </summary>
    public int total_count { get; set; }

    /// <summary>
    /// 文件列表  包括文件夹
    /// </summary>
    public List<FileList> file_list { get; set; }

    public ResponseManageMessage()
    {
        file_list = new List<FileList>();
    }
}

public class FileList
{
    /// <summary>
    /// 是否文件夹
    /// </summary>
    public bool is_dir { get; set; }

    /// <summary>
    /// 是否有文件  就是这个文件夹里有文件吗
    /// </summary>
    public bool has_file { get; set; }

    /// <summary>
    /// 文件大小  文件夹为0
    /// </summary>
    public long filesize { get; set; }

    /// <summary>
    /// 是否图片
    /// </summary>
    public bool is_photo { get; set; }

    /// <summary>
    /// 文件类型
    /// </summary>
    public string filetype { get; set; }

    /// <summary>
    /// 文件名
    /// </summary>
    public string filename { get; set; }

    /// <summary>
    /// 最后一次修改日期
    /// </summary>
    public string datetime { get; set; }
}

UploadFileType类

public enum UploadFileType
{
    image = 0,  //图片
    file = 1,   //文件
    flash = 2,  //flash
    media = 3   //多媒体
}

空间管理排序类

/// <summary>
/// 用于kineditor文本编辑器  文件名排序
/// </summary>
public class NameSorter : IComparer
{
    public int Compare(object x, object y)
    {
        if (x == null && y == null)
        {
            return 0;
        }
        if (x == null)
        {
            return -1;
        }
        if (y == null)
        {
            return 1;
        }
        FileInfo xInfo = new FileInfo(x.ToString());
        FileInfo yInfo = new FileInfo(y.ToString());

        return xInfo.FullName.CompareTo(yInfo.FullName);
    }
}

/// <summary>
/// 用于kineditor文本编辑器  文件大小排序
/// </summary>
public class SizeSorter : IComparer
{
    public int Compare(object x, object y)
    {
        if (x == null && y == null)
        {
            return 0;
        }
        if (x == null)
        {
            return -1;
        }
        if (y == null)
        {
            return 1;
        }
        FileInfo xInfo = new FileInfo(x.ToString());
        FileInfo yInfo = new FileInfo(y.ToString());

        return xInfo.Length.CompareTo(yInfo.Length);
    }
}

/// <summary>
/// 用于kineditor文本编辑器  文件类型大小排序
/// </summary>
public class TypeSorter : IComparer
{
    public int Compare(object x, object y)
    {
        if (x == null && y == null)
        {
            return 0;
        }
        if (x == null)
        {
            return -1;
        }
        if (y == null)
        {
            return 1;
        }
        FileInfo xInfo = new FileInfo(x.ToString());
        FileInfo yInfo = new FileInfo(y.ToString());

        return xInfo.Extension.CompareTo(yInfo.Extension);
    }
}

public class TimeSorter : IComparer
{
    public int Compare(object x, object y)
    {
        if (x == null && y == null)
        {
            return 0;
        }
        if (x == null)
        {
            return -1;
        }
        if (y == null)
        {
            return 1;
        }
        FileInfo xInfo = new FileInfo(x.ToString());
        FileInfo yInfo = new FileInfo(y.ToString());

        return xInfo.LastWriteTime.CompareTo(yInfo.LastWriteTime);
    }
}

三、使用

    public JsonResult Upload(RequestUploadMessage model)
    {
        model.savePath = String.Format(@"f:\richtextbox\{0}\", model.dir.ToString());
        model.webUrl = String.Format("http://localhost:52527/richtextbox/{0}/", model.dir.ToString());
        ResponseUploadMessage result = KindeditorHelper.Upload(model);
        return Json(result, JsonRequestBehavior.DenyGet);
    }

    public JsonResult FileManager(RequestManageMessage model)
    {
        model.webUrl = String.Format("http://localhost:52527/richtextbox/{0}/", model.dir.ToString());
        model.savePath = String.Format(@"f:\richtextbox\{0}\", model.dir.ToString());

        ResponseManageMessage result = KindeditorHelper.Manage(model);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

 

posted @ 2018-12-14 17:12  a boy  阅读(1739)  评论(0编辑  收藏  举报