前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#笔记:Ueditor上传文件引入数据库

C#笔记:Ueditor上传文件引入数据库

作者头像
超级大猪
发布2019-11-22 11:44:41
6180
发布2019-11-22 11:44:41
举报
文章被收录于专栏:大猪的笔记大猪的笔记

项目下载:http://pan.baidu.com/s/1gd8aJvH 密码:qu4c

改造目的:引入数据库进行文件的管理

1、找到config.json,改

代码语言:javascript
复制
 "filePathFormat": "upload/file/{time}{rand:6}", //其实不改也没关系。

2、找到UploadHander.cs,改成下面这样。这样就能在上传的时候进行入库

代码语言:javascript
复制
if (!Directory.Exists(Path.GetDirectoryName(localPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(localPath));
            }
            File.WriteAllBytes(localPath, uploadFileBytes);
            Result.Url = savePath;
            Result.State = UploadState.Success;
            /*下面进行数据库处理*/
            UEditor示例网站.Models.File fileInfo = new UEditor示例网站.Models.File();
            fileInfo.FileName = Result.OriginFileName;
            fileInfo.FilePath = savePath;
            fileInfo.Id = Guid.NewGuid().ToString();
            fileInfo.UploaderId = 1; //这里记录上传者的ID。随便写了个1。
            fileInfo.SaveOrUpdate();

3、配合自带的文件管理器显示数据库中的文件。而不是遍历文件夹。 

1)修改了ListFileHander.cs默认的FileList的类型,默认是List<string>。不太利于完成我们的任务。 2)添加一个新的内部类 FileInfo,把FileList改成List<FileInfo>类型.

3)writeresult也要进行修改以适配FileList类型的变化。

4)添加新的类 DataBaseListFileHander.cs继承ListFileHander。里面添加读取数据库的处理。

改的地方太多了。直接贴代码了。

代码语言:javascript
复制
public class ListFileManager : Handler
{
    public enum ResultState
    {
        Success,
        InvalidParam,
        AuthorizError,
        IOError,
        PathNotFound
    }
    public class FileInfo //1、增加一个内部类,来完成使命
    {
        public string Url;//上传文件的路径
        public string Title;//名字
    }
    public int Start;
    public int Size;
    public int Total;
    public ResultState State;
    public String PathToList;
    public List<FileInfo> FileList;//2、默认的string已经不能完成任务了
    public String[] SearchExtensions;
    public ListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
        : base(context)
    {
        this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
        this.PathToList = pathToList;
    }
    public override void Process()
    {
        try
        {
            Start = String.IsNullOrEmpty(Request["start"]) ? 0 : Convert.ToInt32(Request["start"]);
            Size = String.IsNullOrEmpty(Request["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request["size"]);
        }
        catch (FormatException)
        {
            State = ResultState.InvalidParam;
            WriteResult();
            return;
        }
        var buildingList = new List<String>();
        try
        {
            var localPath = Server.MapPath(PathToList);
            buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
                .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
                .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
            Total = buildingList.Count;
            var templist = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
            foreach (var item in templist)
            {
                FileList.Add(new FileInfo() { Url = item, Title = item });
            }
        }
        catch (UnauthorizedAccessException)
        {
            State = ResultState.AuthorizError;
        }
        catch (DirectoryNotFoundException)
        {
            State = ResultState.PathNotFound;
        }
        catch (IOException)
        {
            State = ResultState.IOError;
        }
        finally
        {
            WriteResult();
        }
    }
    public void WriteResult()//这个函数也因为实体改变,需要进行一点修正
    {
        WriteJson(new
        {
            state = GetStateString(),
            list = FileList == null ? null : FileList.Select(x => new { url = x.Url, title = x.Title }),
            start = Start,
            size = Size,
            total = Total
        });
    }
    private string GetStateString()
    {
        switch (State)
        {
            case ResultState.Success:
                return "SUCCESS";
            case ResultState.InvalidParam:
                return "参数不正确";
            case ResultState.PathNotFound:
                return "路径不存在";
            case ResultState.AuthorizError:
                return "文件系统权限不足";
            case ResultState.IOError:
                return "文件系统读取错误";
        }
        return "未知错误";
    }
}
public class DataBaseListFileManager : ListFileManager
{
    public DataBaseListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
        : base(context, pathToList, searchExtensions)
    {
    }
    public override void Process()
    {
        try
        {
            Start = String.IsNullOrEmpty(Request["start"]) ? 0 : Convert.ToInt32(Request["start"]);
            Size = String.IsNullOrEmpty(Request["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request["size"]);
        }
        catch (FormatException)
        {
            State = ResultState.InvalidParam;
            WriteResult();
            return;
        }
        var buildingList = new List<FileInfo>();
        try
        {
            var localPath = Server.MapPath(PathToList);
            //buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
            //    .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
            //    .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //这里把原来的注释掉,改成从数据库里取数据 
            string xmlpath = UEditor示例网站.Controllers.HomeController.fileInfoXmlPath;
            var nodes = XmlHelper.Search(xmlpath, "File", "UploaderId#1");
            foreach (var item in nodes)
            {
                buildingList.Add(new FileInfo() { Url = item.Value, Title = item.Attribute("FileName").Value });
            }
            FileList = buildingList.OrderBy(x => x.Url).Skip(Start).Take(Size).ToList();
            Total = buildingList.Count;
            
        }
        catch (UnauthorizedAccessException)
        {
            State = ResultState.AuthorizError;
        }
        catch (DirectoryNotFoundException)
        {
            State = ResultState.PathNotFound;
        }
        catch (IOException)
        {
            State = ResultState.IOError;
        }
        finally
        {
            WriteResult();
        }
    }
}

4、因为在上面,我们把传入的json已经添加了新的信息。前台相应的js需要进行修改。打开attachment.js。

修改PushData函数。

代码语言:javascript
复制
 /* 添加图片到列表界面上 */
        pushData: function (list) {
            var i, item, img, filetype, preview, icon, _this = this,
                urlPrefix = editor.getOpt('fileManagerUrlPrefix');
            for (i = 0; i < list.length; i++) {
                if(list[i] && list[i].url) {
                    item = document.createElement('li');
                    icon = document.createElement('span');
                    filetype = list[i].url.substr(list[i].url.lastIndexOf('.') + 1);
                    if ( "png|jpg|jpeg|gif|bmp".indexOf(filetype) != -1 ) {
                        preview = document.createElement('img');
                        domUtils.on(preview, 'load', (function(image){
                            return function(){
                                _this.scale(image, image.parentNode.offsetWidth, image.parentNode.offsetHeight);
                            };
                        })(preview));
                        preview.width = 113;
                        preview.setAttribute('src', urlPrefix + list[i].url + (list[i].url.indexOf('?') == -1 ? '?noCache=':'&noCache=') + (+new Date()).toString(36) );
                    } else {
                        var ic = document.createElement('i'),
                            textSpan = document.createElement('span');
                        textSpan.innerHTML = list[i].url.substr(list[i].url.lastIndexOf('/') + 1);
                        //1、把传入的文件名改了。
                        if (list[i].title) {
                            textSpan.innerHTML = list[i].title;
                        }
                        preview = document.createElement('div');
                        preview.appendChild(ic);
                        preview.appendChild(textSpan);
                        domUtils.addClass(preview, 'file-wrapper');
                        domUtils.addClass(textSpan, 'file-title');
                        domUtils.addClass(ic, 'file-type-' + filetype);
                        domUtils.addClass(ic, 'file-preview');
                    }
                    domUtils.addClass(icon, 'icon');
                    item.setAttribute('data-url', urlPrefix + list[i].url);
                    if (list[i].original) {
                        item.setAttribute('data-title', list[i].original);
                    }
                    //alert(list[i].title);
                    //2、把传入的文件名改了。好了,完工了。
                    if (list[i].title) {
                        item.setAttribute('data-title', list[i].title);
                    }
                    item.appendChild(preview);
                    item.appendChild(icon);
                    this.list.insertBefore(item, this.clearFloat);
                }
            }
        },

4、最后,把调用的地方改了。Controller.ashx

代码语言:javascript
复制
 case "listfile":
                action = new DataBaseListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                break;

完工了。应该还是比较简单吧。具体的关系很容易就能弄清。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-03-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档