1. 程式人生 > >【Kindeditor編輯器】 檔案上傳、空間管理

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