【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);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM