C#笔记:Ueditor上传文件引入数据库
- 2019 年 11 月 22 日
- 筆記
项目下载:http://pan.baidu.com/s/1gd8aJvH 密码:qu4c
改造目的:引入数据库进行文件的管理
1、找到config.json,改
"filePathFormat": "upload/file/{time}{rand:6}", //其实不改也没关系。
2、找到UploadHander.cs,改成下面这样。这样就能在上传的时候进行入库
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。里面添加读取数据库的处理。
改的地方太多了。直接贴代码了。
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函数。
/* 添加图片到列表界面上 */ 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
case "listfile": action = new DataBaseListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles")); break;
完工了。应该还是比较简单吧。具体的关系很容易就能弄清。