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;

完工了。應該還是比較簡單吧。具體的關係很容易就能弄清。