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

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

作者头像
超级大猪
发布于 2019-11-22 03:44:41
发布于 2019-11-22 03:44:41
67000
代码可运行
举报
文章被收录于专栏:大猪的笔记大猪的笔记
运行总次数:0
代码可运行

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

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

1、找到config.json,改

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 "filePathFormat": "upload/file/{time}{rand:6}", //其实不改也没关系。

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
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
代码运行次数:0
运行
AI代码解释
复制
 /* 添加图片到列表界面上 */
        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
代码运行次数:0
运行
AI代码解释
复制
 case "listfile":
                action = new DataBaseListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
                break;

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

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

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

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

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

评论
登录后参与评论
暂无评论
推荐阅读
MVC5+EasyUI+EF6增删改查以及登录登出的演示
创建StudentController、 及Index视图, 在Index上按F5运行
明志德道
2023/10/21
2610
MVC5+EasyUI+EF6增删改查以及登录登出的演示
easyui+ssm+shiro做的登录注册修改密码审核用户添加角色(五)
easyui+ssm+shiro做的登录注册修改密码审核用户添加角色(五)
Java架构师必看
2021/04/13
1.6K1
easyui+ssm+shiro做的登录注册修改密码审核用户添加角色(五)
利用easyui实现增删改查:ssm项目的全部代码
index.jsp页面 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <link rel="stylesheet" type="text/css" href="/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="/themes/icon.css"> <script type="text/javasc
一写代码就开心
2020/11/19
1.5K0
利用easyui实现增删改查:ssm项目的全部代码
利用easyui实现增删改查(四):修改数据
数据列表后面是有修改的按钮,点击之后,会弹出一个模态框,并且对应的数据是会回填到模态框,之后我们修改之后,点击模态框里面的修改按钮,那么就可以将修改的数据传到后台,这样就可以完成修改功能
一写代码就开心
2020/11/19
6620
利用easyui实现增删改查(四):修改数据
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(9)-MVC与EasyUI结合增删改查
文章于2016-12-17日重写 在第八讲中,我们已经做到了怎么样分页。这一讲主要讲增删改查。第六讲的代码已经给出,里面包含了增删改,大家可以下载下来看下。 这讲主要是,制作漂亮的工具栏,虽然ea
用户1149182
2018/01/16
1.9K0
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(9)-MVC与EasyUI结合增删改查
利用easyui实现增删改查(四):添加数据
写了以上的代码,那么就有模态框了,只是我们看不见,因为 closed:true 关闭了
一写代码就开心
2020/11/19
6500
利用easyui实现增删改查(四):添加数据
【php增删改查实例】第十节 - 部门管理模块(新增功能)
正常情况下,在一个部门管理页面,不仅仅需要展示列表数据,还需要基本的增删改操作,所以,我们先把之前写好的新增功能集成进来。 在toolbar中,添加一个新增按钮。 <div id="toolbar" style="padding:10px 12px;"> <a href="javascript:openDialog()" class="easyui-linkbutton" iconCls="icon-add" plain="true">新增部门</a> <br><br> 请输入
剽悍一小兔
2018/06/21
7800
thinkjs crud练习
该文章介绍了一种使用 ES6 实现模板引擎,并使用 ThinkJS 引擎进行模板渲染的方法。该方法包括配置 ES6 环境、定义模板引擎接口、实现模板引擎基类、定义模板语法、实现模板编译和渲染、编写测试用例和代码示例。
用户1141560
2017/12/26
1.5K0
thinkjs crud练习
easy的jsp的增删改查在一个jsp页面上
easy的jsp的增删改查在一个jsp页面上
Java架构师必看
2021/05/14
4.6K0
jquery的增删改查
全栈若城
2024/02/29
1050
jquery的增删改查
初试JqueryEasyUI(附Demo)[通俗易懂]
  关于easyui不多说,对于我们这样没有美术功底的程序员来说,简直是大大的福利,园里面也有不少人在用,自己在整理一个个站,后台管理要用,正好可以学习下。网上找了相关的教程什么的,但是发现还是官网上的demo讲的狠详细,还有就是下载后的demo示例,但都是某个控件示例,很遗憾,没有整个系统的demo。
全栈程序员站长
2022/09/07
2K0
初试JqueryEasyUI(附Demo)[通俗易懂]
ssm整合3.easyui
用户9184480
2024/12/13
720
【Java框架型项目从入门到装逼】第十一节 用户新增之把数据传递到后台
让我们继续来做“主线任务”,这一节,我们来做具体的用户新增功能。首先,为了简单起见,我把主页面改了一些,改的是列表那一块。删去了一些字段,和数据库表对应一致: 现在,我们要实现一个效果,就是当我点击新
剽悍一小兔
2018/05/17
1.5K0
Nodejs+Express+Mysql实现简单用户管理增删改查
https://github.com/king-y/NodeJs/tree/master/user
思索
2024/08/16
600
Nodejs+Express+Mysql实现简单用户管理增删改查
使用jquery-easyui写的CRUD插件(2)
首先定义变量 var options = jQuery.extend({},jQuery.fn.crudUIGrid.defaults, options); var addTypeName = options.addTypeName;//添加div的页面的名称,默认是type-window var formId = options.formId;//要操作的form的名称 var title = options.title;
cloudskyme
2018/03/19
1.7K0
基于asp.net + easyui框架,一步步学习easyui-datagrid—实现添加、编辑、删除
基于asp.net + easyui框架,一步步学习easyui-datagrid——界面(一)
程序猿小亮
2021/01/29
1.6K0
javaWeb核心技术第十四篇之easyui
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
海仔
2019/09/18
1.2K0
jQuery EasyUI+ashx实现数据库的CIUD操作
对上一个小项目做一个回顾总结,涉及到了jQuery EasyUI+ashx实现数据库的CIUD操作,和大家分享一下。基本思路是用easyui做前端,ashx做后端,中间使用json格式交换数据,其中json主要使用Newtonsoft.Json来序列化和反序列化,为简单起见,后端没有分层,数据都是靠拼接sql,使用一个简单封装的DBHelper来时间数据库的操作。
全栈程序员站长
2022/11/15
1K0
jQuery EasyUI+ashx实现数据库的CIUD操作
实现销售合同结存条件
实现销售合同结存条件
Java架构师必看
2021/05/14
9630
实现销售合同结存条件
easyui常用组件
表单 日期选择(html初始化) <input name="tadminModel.birthday" class="easyui-validatebox Wdate" style="width: 370px;" onclick="WdatePicker({dateFmt:'yyyy-MM-dd',position:{right:0,top:0}})"/> 按钮(html初始化) <a type="button" href="javascript:;" class="easyui-linkbutton" i
码客说
2019/10/22
2.4K0
推荐阅读
相关推荐
MVC5+EasyUI+EF6增删改查以及登录登出的演示
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文