忽略dll文件git

This commit is contained in:
“wanyongkang”
2023-07-29 10:19:42 +08:00
parent 7f97317bcc
commit b562aba2b1
3868 changed files with 63608 additions and 385427 deletions

View File

@@ -1,121 +1,121 @@
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Linq;
namespace UEditor.Core.Handlers
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class AliUploadHandler : UploadHandler
{
public AliUploadHandler(HttpContext context)
: base(context)
{
}
public UploadService Uploader { get; set; }
public override UEditorResult Process()
{
string uploadFileName = "";
Stream stream = default(Stream);
if (UploadConfig.Base64)
{
uploadFileName = UploadConfig.Base64Filename;
var uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]);
stream = new MemoryStream(uploadFileBytes);
}
else
{
var file = Request.Form.Files[UploadConfig.UploadFieldName];
uploadFileName = file.FileName;
if (!CheckFileType(uploadFileName))
{
Result.State = UploadState.TypeNotAllow;
return WriteResult();
}
if (!CheckFileSize(file.Length))
{
Result.State = UploadState.SizeLimitExceed;
return WriteResult();
}
try
{
stream = file.OpenReadStream();
}
catch (Exception)
{
Result.State = UploadState.NetworkError;
WriteResult();
}
}
var fileKey = DateTime.Now.Ticks + new Random((int)DateTime.Now.Ticks).Next(0, 100000).ToString();
Result.OriginFileName = uploadFileName;
UEditorResult result;
try
{
fileKey = $"{fileKey.ToString()}{Path.GetExtension(uploadFileName)}";
var ret = Uploader.AliYunUpload(fileKey, Result.OriginFileName, stream);
Result.Url = ret.Url;
Result.State = UploadState.Success;
}
catch (Exception e)
{
Result.State = UploadState.FileAccessError;
Result.ErrorMessage = e.Message;
}
finally
{
result = WriteResult();
}
return result;
}
private UEditorResult WriteResult()
{
return new UEditorResult
{
State = GetStateMessage(Result.State),
Url = Result.Url,
Title = Result.OriginFileName,
Original = Result.OriginFileName,
Error = Result.ErrorMessage
};
}
private string GetStateMessage(UploadState state)
{
switch (state)
{
case UploadState.Success:
return "SUCCESS";
case UploadState.FileAccessError:
return "文件访问出错,请检查写入权限";
case UploadState.SizeLimitExceed:
return "文件大小超出服务器限制";
case UploadState.TypeNotAllow:
return "不允许的文件格式";
case UploadState.NetworkError:
return "网络错误";
}
return "未知错误";
}
private bool CheckFileType(string filename)
{
var fileExtension = Path.GetExtension(filename).ToLower();
return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
}
private bool CheckFileSize(long size)
{
return size < UploadConfig.SizeLimit;
}
}
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Linq;
namespace UEditor.Core.Handlers
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class AliUploadHandler : UploadHandler
{
public AliUploadHandler(HttpContext context)
: base(context)
{
}
public UploadService Uploader { get; set; }
public override UEditorResult Process()
{
string uploadFileName = "";
Stream stream = default(Stream);
if (UploadConfig.Base64)
{
uploadFileName = UploadConfig.Base64Filename;
var uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]);
stream = new MemoryStream(uploadFileBytes);
}
else
{
var file = Request.Form.Files[UploadConfig.UploadFieldName];
uploadFileName = file.FileName;
if (!CheckFileType(uploadFileName))
{
Result.State = UploadState.TypeNotAllow;
return WriteResult();
}
if (!CheckFileSize(file.Length))
{
Result.State = UploadState.SizeLimitExceed;
return WriteResult();
}
try
{
stream = file.OpenReadStream();
}
catch (Exception)
{
Result.State = UploadState.NetworkError;
WriteResult();
}
}
var fileKey = DateTime.Now.Ticks + new Random((int)DateTime.Now.Ticks).Next(0, 100000).ToString();
Result.OriginFileName = uploadFileName;
UEditorResult result;
try
{
fileKey = $"{fileKey.ToString()}{Path.GetExtension(uploadFileName)}";
var ret = Uploader.AliYunUpload(fileKey, Result.OriginFileName, stream);
Result.Url = ret.Url;
Result.State = UploadState.Success;
}
catch (Exception e)
{
Result.State = UploadState.FileAccessError;
Result.ErrorMessage = e.Message;
}
finally
{
result = WriteResult();
}
return result;
}
private UEditorResult WriteResult()
{
return new UEditorResult
{
State = GetStateMessage(Result.State),
Url = Result.Url,
Title = Result.OriginFileName,
Original = Result.OriginFileName,
Error = Result.ErrorMessage
};
}
private string GetStateMessage(UploadState state)
{
switch (state)
{
case UploadState.Success:
return "SUCCESS";
case UploadState.FileAccessError:
return "文件访问出错,请检查写入权限";
case UploadState.SizeLimitExceed:
return "文件大小超出服务器限制";
case UploadState.TypeNotAllow:
return "不允许的文件格式";
case UploadState.NetworkError:
return "网络错误";
}
return "未知错误";
}
private bool CheckFileType(string filename)
{
var fileExtension = Path.GetExtension(filename).ToLower();
return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
}
private bool CheckFileSize(long size)
{
return size < UploadConfig.SizeLimit;
}
}
}

View File

@@ -1,15 +1,15 @@
using Newtonsoft.Json.Linq;
namespace UEditor.Core.Handlers
{
/// <summary>
/// Config 的摘要说明
/// </summary>
public class ConfigHandler
{
public JObject Process()
{
return Config.Items;
}
}
using Newtonsoft.Json.Linq;
namespace UEditor.Core.Handlers
{
/// <summary>
/// Config 的摘要说明
/// </summary>
public class ConfigHandler
{
public JObject Process()
{
return Config.Items;
}
}
}

View File

@@ -1,177 +1,177 @@
using System;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
public class CrawlerHandler : Handler
{
private string[] _sources;
private Crawler[] _crawlers;
public CrawlerHandler(HttpContext context) : base(context) { }
public override UEditorResult Process()
{
_sources = Request.Form["source[]"];
//fixed bug:https://github.com/baiyunchen/UEditor.Core/pull/5
if (_sources == null || _sources.Length == 0)
{
_sources = Request.Query["source[]"];
}
if (_sources == null || _sources.Length == 0)
{
return new UEditorResult
{
State = "参数错误:没有指定抓取源"
};
}
_crawlers = _sources.Select(x => new Crawler(x).Fetch()).ToArray();
return new UEditorResult
{
State = "SUCCESS",
List = _crawlers.Select(x => new UEditorFileList
{
State = x.State,
Source = x.SourceUrl,
Url = x.ServerUrl
})
};
}
}
public class Crawler
{
public string SourceUrl { get; set; }
public string ServerUrl { get; set; }
public string State { get; set; }
public Crawler(string sourceUrl)
{
this.SourceUrl = sourceUrl;
}
public Crawler Fetch()
{
if (!IsExternalIpAddress(this.SourceUrl))
{
State = "INVALID_URL";
return this;
}
var request = WebRequest.Create(this.SourceUrl) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null && response.StatusCode != HttpStatusCode.OK)
{
State = "Url returns " + response.StatusCode + ", " + response.StatusDescription;
return this;
}
if (response != null && response.ContentType.IndexOf("image", StringComparison.Ordinal) == -1)
{
State = "Url is not an image";
return this;
}
var sourceUri = new Uri(this.SourceUrl);
ServerUrl = PathFormatter.Format(Path.GetFileName(sourceUri.AbsolutePath), Config.GetString("catcherPathFormat"));
var savePath = Path.Combine(Config.WebRootPath, ServerUrl);
if (!Directory.Exists(Path.GetDirectoryName(savePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
}
try
{
if (response != null)
{
var stream = response.GetResponseStream();
var reader = new BinaryReader(stream);
byte[] bytes;
using (var ms = new MemoryStream())
{
byte[] buffer = new byte[4096];
int count;
while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, count);
}
bytes = ms.ToArray();
}
File.WriteAllBytes(savePath, bytes);
}
State = "SUCCESS";
}
catch (Exception e)
{
State = "抓取错误:" + e.Message;
}
return this;
}
}
private bool IsExternalIpAddress(string url)
{
var uri = new Uri(url);
switch (uri.HostNameType)
{
case UriHostNameType.Dns:
var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
foreach (IPAddress ipAddress in ipHostEntry.AddressList)
{
byte[] ipBytes = ipAddress.GetAddressBytes();
if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (!IsPrivateIP(ipAddress))
{
return true;
}
}
}
break;
case UriHostNameType.IPv4:
return !IsPrivateIP(IPAddress.Parse(uri.DnsSafeHost));
}
return false;
}
private bool IsPrivateIP(IPAddress myIpAddress)
{
if (IPAddress.IsLoopback(myIpAddress)) return true;
if (myIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
byte[] ipBytes = myIpAddress.GetAddressBytes();
// 10.0.0.0/24
if (ipBytes[0] == 10)
{
return true;
}
// 172.16.0.0/16
else if (ipBytes[0] == 172 && ipBytes[1] == 16)
{
return true;
}
// 192.168.0.0/16
else if (ipBytes[0] == 192 && ipBytes[1] == 168)
{
return true;
}
// 169.254.0.0/16
else if (ipBytes[0] == 169 && ipBytes[1] == 254)
{
return true;
}
}
return false;
}
}
}
using System;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
public class CrawlerHandler : Handler
{
private string[] _sources;
private Crawler[] _crawlers;
public CrawlerHandler(HttpContext context) : base(context) { }
public override UEditorResult Process()
{
_sources = Request.Form["source[]"];
//fixed bug:https://github.com/baiyunchen/UEditor.Core/pull/5
if (_sources == null || _sources.Length == 0)
{
_sources = Request.Query["source[]"];
}
if (_sources == null || _sources.Length == 0)
{
return new UEditorResult
{
State = "参数错误:没有指定抓取源"
};
}
_crawlers = _sources.Select(x => new Crawler(x).Fetch()).ToArray();
return new UEditorResult
{
State = "SUCCESS",
List = _crawlers.Select(x => new UEditorFileList
{
State = x.State,
Source = x.SourceUrl,
Url = x.ServerUrl
})
};
}
}
public class Crawler
{
public string SourceUrl { get; set; }
public string ServerUrl { get; set; }
public string State { get; set; }
public Crawler(string sourceUrl)
{
this.SourceUrl = sourceUrl;
}
public Crawler Fetch()
{
if (!IsExternalIpAddress(this.SourceUrl))
{
State = "INVALID_URL";
return this;
}
var request = WebRequest.Create(this.SourceUrl) as HttpWebRequest;
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null && response.StatusCode != HttpStatusCode.OK)
{
State = "Url returns " + response.StatusCode + ", " + response.StatusDescription;
return this;
}
if (response != null && response.ContentType.IndexOf("image", StringComparison.Ordinal) == -1)
{
State = "Url is not an image";
return this;
}
var sourceUri = new Uri(this.SourceUrl);
ServerUrl = PathFormatter.Format(Path.GetFileName(sourceUri.AbsolutePath), Config.GetString("catcherPathFormat"));
var savePath = Path.Combine(Config.WebRootPath, ServerUrl);
if (!Directory.Exists(Path.GetDirectoryName(savePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
}
try
{
if (response != null)
{
var stream = response.GetResponseStream();
var reader = new BinaryReader(stream);
byte[] bytes;
using (var ms = new MemoryStream())
{
byte[] buffer = new byte[4096];
int count;
while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, count);
}
bytes = ms.ToArray();
}
File.WriteAllBytes(savePath, bytes);
}
State = "SUCCESS";
}
catch (Exception e)
{
State = "抓取错误:" + e.Message;
}
return this;
}
}
private bool IsExternalIpAddress(string url)
{
var uri = new Uri(url);
switch (uri.HostNameType)
{
case UriHostNameType.Dns:
var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
foreach (IPAddress ipAddress in ipHostEntry.AddressList)
{
byte[] ipBytes = ipAddress.GetAddressBytes();
if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
if (!IsPrivateIP(ipAddress))
{
return true;
}
}
}
break;
case UriHostNameType.IPv4:
return !IsPrivateIP(IPAddress.Parse(uri.DnsSafeHost));
}
return false;
}
private bool IsPrivateIP(IPAddress myIpAddress)
{
if (IPAddress.IsLoopback(myIpAddress)) return true;
if (myIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
byte[] ipBytes = myIpAddress.GetAddressBytes();
// 10.0.0.0/24
if (ipBytes[0] == 10)
{
return true;
}
// 172.16.0.0/16
else if (ipBytes[0] == 172 && ipBytes[1] == 16)
{
return true;
}
// 192.168.0.0/16
else if (ipBytes[0] == 192 && ipBytes[1] == 168)
{
return true;
}
// 169.254.0.0/16
else if (ipBytes[0] == 169 && ipBytes[1] == 254)
{
return true;
}
}
return false;
}
}
}

View File

@@ -1,76 +1,76 @@
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
public class HandelFactory
{
public static Handler GetHandler(string action, HttpContext context, UploadService m_UploadService)
{
switch (action)
{
case AppConsts.Action.UploadImage:
return new UploadHandler(context)
{
//Uploader= m_UploadService,
UploadConfig = new UploadConfig
{
AllowExtensions = Config.GetStringList("imageAllowFiles"),
PathFormat = Config.GetString("imagePathFormat"),
SizeLimit = Config.GetInt("imageMaxSize"),
UploadFieldName = Config.GetString("imageFieldName")
}
};
case AppConsts.Action.UploadScrawl:
return new UploadHandler(context)
{
//Uploader = m_UploadService,
UploadConfig = new UploadConfig()
{
AllowExtensions = new string[] { ".png" },
PathFormat = Config.GetString("scrawlPathFormat"),
SizeLimit = Config.GetInt("scrawlMaxSize"),
UploadFieldName = Config.GetString("scrawlFieldName"),
Base64 = true,
Base64Filename = "scrawl.png"
}
};
case AppConsts.Action.UploadVideo:
return new UploadHandler(context)
{
//Uploader = m_UploadService,
UploadConfig = new UploadConfig()
{
AllowExtensions = Config.GetStringList("videoAllowFiles"),
PathFormat = Config.GetString("videoPathFormat"),
SizeLimit = Config.GetInt("videoMaxSize"),
UploadFieldName = Config.GetString("videoFieldName")
}
};
case AppConsts.Action.UploadFile:
return new UploadHandler(context)
{
//Uploader = m_UploadService,
UploadConfig = new UploadConfig()
{
AllowExtensions = Config.GetStringList("fileAllowFiles"),
PathFormat = Config.GetString("filePathFormat"),
SizeLimit = Config.GetInt("fileMaxSize"),
UploadFieldName = Config.GetString("fileFieldName")
}
};
case AppConsts.Action.ListImage:
return new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
case AppConsts.Action.ListFile:
return new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
case AppConsts.Action.CatchImage:
return new CrawlerHandler(context);
default:
return new NotSupportedHandler(context);
}
}
}
}
using Hncore.Pass.Vpn.Service;
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
public class HandelFactory
{
public static Handler GetHandler(string action, HttpContext context, UploadService m_UploadService)
{
switch (action)
{
case AppConsts.Action.UploadImage:
return new UploadHandler(context)
{
//Uploader= m_UploadService,
UploadConfig = new UploadConfig
{
AllowExtensions = Config.GetStringList("imageAllowFiles"),
PathFormat = Config.GetString("imagePathFormat"),
SizeLimit = Config.GetInt("imageMaxSize"),
UploadFieldName = Config.GetString("imageFieldName")
}
};
case AppConsts.Action.UploadScrawl:
return new UploadHandler(context)
{
//Uploader = m_UploadService,
UploadConfig = new UploadConfig()
{
AllowExtensions = new string[] { ".png" },
PathFormat = Config.GetString("scrawlPathFormat"),
SizeLimit = Config.GetInt("scrawlMaxSize"),
UploadFieldName = Config.GetString("scrawlFieldName"),
Base64 = true,
Base64Filename = "scrawl.png"
}
};
case AppConsts.Action.UploadVideo:
return new UploadHandler(context)
{
//Uploader = m_UploadService,
UploadConfig = new UploadConfig()
{
AllowExtensions = Config.GetStringList("videoAllowFiles"),
PathFormat = Config.GetString("videoPathFormat"),
SizeLimit = Config.GetInt("videoMaxSize"),
UploadFieldName = Config.GetString("videoFieldName")
}
};
case AppConsts.Action.UploadFile:
return new UploadHandler(context)
{
//Uploader = m_UploadService,
UploadConfig = new UploadConfig()
{
AllowExtensions = Config.GetStringList("fileAllowFiles"),
PathFormat = Config.GetString("filePathFormat"),
SizeLimit = Config.GetInt("fileMaxSize"),
UploadFieldName = Config.GetString("fileFieldName")
}
};
case AppConsts.Action.ListImage:
return new ListFileManager(context, Config.GetString("imageManagerListPath"), Config.GetStringList("imageManagerAllowFiles"));
case AppConsts.Action.ListFile:
return new ListFileManager(context, Config.GetString("fileManagerListPath"), Config.GetStringList("fileManagerAllowFiles"));
case AppConsts.Action.CatchImage:
return new CrawlerHandler(context);
default:
return new NotSupportedHandler(context);
}
}
}
}

View File

@@ -1,21 +1,21 @@
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
public abstract class Handler
{
public Handler(HttpContext context)
{
this.Request = context.Request;
this.Response = context.Response;
this.Context = context;
}
public abstract UEditorResult Process();
public HttpRequest Request { get; private set; }
public HttpResponse Response { get; private set; }
public HttpContext Context { get; private set; }
}
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
public abstract class Handler
{
public Handler(HttpContext context)
{
this.Request = context.Request;
this.Response = context.Response;
this.Context = context;
}
public abstract UEditorResult Process();
public HttpRequest Request { get; private set; }
public HttpResponse Response { get; private set; }
public HttpContext Context { get; private set; }
}
}

View File

@@ -1,113 +1,113 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace UEditor.Core.Handlers
{
/// <summary>
/// FileManager 的摘要说明
/// </summary>
public class ListFileManager : Handler
{
enum ResultState
{
Success,
InvalidParam,
AuthorizError,
IOError,
PathNotFound
}
private int Start;
private int Size;
private int Total;
private ResultState State;
private String PathToList;
private String[] FileList;
private 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 UEditorResult Process()
{
try
{
Start = string.IsNullOrWhiteSpace(Request.Query["start"]) ? 0 : Convert.ToInt32(Request.Query["start"]);
Size = string.IsNullOrWhiteSpace(Request.Query["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request.Query["size"]);
}
catch (FormatException)
{
State = ResultState.InvalidParam;
return WriteResult();
}
UEditorResult result;
var buildingList = new List<String>();
try
{
var localPath = Path.Combine(Config.WebRootPath, 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;
FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
}
catch (UnauthorizedAccessException)
{
State = ResultState.AuthorizError;
}
catch (DirectoryNotFoundException)
{
State = ResultState.PathNotFound;
}
catch (IOException)
{
State = ResultState.IOError;
}
finally
{
result = WriteResult();
}
return result;
}
private UEditorResult WriteResult()
{
return new UEditorResult
{
State = GetStateString(),
List = FileList?.Select(x => new UEditorFileList { Url = x }),
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 "未知错误";
}
}
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace UEditor.Core.Handlers
{
/// <summary>
/// FileManager 的摘要说明
/// </summary>
public class ListFileManager : Handler
{
enum ResultState
{
Success,
InvalidParam,
AuthorizError,
IOError,
PathNotFound
}
private int Start;
private int Size;
private int Total;
private ResultState State;
private String PathToList;
private String[] FileList;
private 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 UEditorResult Process()
{
try
{
Start = string.IsNullOrWhiteSpace(Request.Query["start"]) ? 0 : Convert.ToInt32(Request.Query["start"]);
Size = string.IsNullOrWhiteSpace(Request.Query["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request.Query["size"]);
}
catch (FormatException)
{
State = ResultState.InvalidParam;
return WriteResult();
}
UEditorResult result;
var buildingList = new List<String>();
try
{
var localPath = Path.Combine(Config.WebRootPath, 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;
FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
}
catch (UnauthorizedAccessException)
{
State = ResultState.AuthorizError;
}
catch (DirectoryNotFoundException)
{
State = ResultState.PathNotFound;
}
catch (IOException)
{
State = ResultState.IOError;
}
finally
{
result = WriteResult();
}
return result;
}
private UEditorResult WriteResult()
{
return new UEditorResult
{
State = GetStateString(),
List = FileList?.Select(x => new UEditorFileList { Url = x }),
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 "未知错误";
}
}
}

View File

@@ -1,25 +1,25 @@
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
/// <summary>
/// NotSupportedHandler 的摘要说明
/// </summary>
public class NotSupportedHandler : Handler
{
public NotSupportedHandler(HttpContext context)
: base(context)
{
}
public override UEditorResult Process()
{
return new UEditorResult
{
State = "action 参数为空或者 action 不被支持。"
};
}
}
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
/// <summary>
/// NotSupportedHandler 的摘要说明
/// </summary>
public class NotSupportedHandler : Handler
{
public NotSupportedHandler(HttpContext context)
: base(context)
{
}
public override UEditorResult Process()
{
return new UEditorResult
{
State = "action 参数为空或者 action 不被支持。"
};
}
}
}

View File

@@ -1,190 +1,190 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class UploadHandler : Handler
{
public UploadConfig UploadConfig { get; set; }
public UploadResult Result { get; private set; }
public UploadHandler(HttpContext context)
: base(context)
{
this.Result = new UploadResult() { State = UploadState.Unknown };
}
public override UEditorResult Process()
{
byte[] uploadFileBytes = null;
string uploadFileName = null;
if (UploadConfig.Base64)
{
uploadFileName = UploadConfig.Base64Filename;
uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]);
}
else
{
var file = Request.Form.Files[UploadConfig.UploadFieldName];
uploadFileName = file.FileName;
if (!CheckFileType(uploadFileName))
{
Result.State = UploadState.TypeNotAllow;
return WriteResult();
}
if (!CheckFileSize(file.Length))
{
Result.State = UploadState.SizeLimitExceed;
return WriteResult();
}
uploadFileBytes = new byte[file.Length];
try
{
file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length);
}
catch (Exception)
{
Result.State = UploadState.NetworkError;
WriteResult();
}
}
Result.OriginFileName = uploadFileName;
var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
var localPath = Path.Combine(Config.WebRootPath,savePath);
UEditorResult result;
try
{
if (!Directory.Exists(Path.GetDirectoryName(localPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(localPath));
}
File.WriteAllBytes(localPath, uploadFileBytes);
Result.Url =savePath;
Result.State = UploadState.Success;
}
catch (Exception e)
{
Result.State = UploadState.FileAccessError;
Result.ErrorMessage = e.Message;
}
finally
{
result = WriteResult();
}
return result;
}
private UEditorResult WriteResult()
{
return new UEditorResult
{
State = GetStateMessage(Result.State),
Url = Result.Url,
Title = Result.OriginFileName,
Original = Result.OriginFileName,
Error = Result.ErrorMessage
};
}
private string GetStateMessage(UploadState state)
{
switch (state)
{
case UploadState.Success:
return "SUCCESS";
case UploadState.FileAccessError:
return "文件访问出错,请检查写入权限";
case UploadState.SizeLimitExceed:
return "文件大小超出服务器限制";
case UploadState.TypeNotAllow:
return "不允许的文件格式";
case UploadState.NetworkError:
return "网络错误";
}
return "未知错误";
}
private bool CheckFileType(string filename)
{
var fileExtension = Path.GetExtension(filename).ToLower();
return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
}
private bool CheckFileSize(long size)
{
return size < UploadConfig.SizeLimit;
}
}
public class UploadConfig
{
/// <summary>
/// 文件命名规则
/// </summary>
public string PathFormat { get; set; }
/// <summary>
/// 上传表单域名称
/// </summary>
public string UploadFieldName { get; set; }
/// <summary>
/// 上传大小限制
/// </summary>
public int SizeLimit { get; set; }
/// <summary>
/// 上传允许的文件格式
/// </summary>
public string[] AllowExtensions { get; set; }
/// <summary>
/// 文件是否以 Base64 的形式上传
/// </summary>
public bool Base64 { get; set; }
/// <summary>
/// Base64 字符串所表示的文件名
/// </summary>
public string Base64Filename { get; set; }
}
public class UploadResult
{
public UploadState State { get; set; }
public string Url { get; set; }
public string OriginFileName { get; set; }
public string ErrorMessage { get; set; }
}
public enum UploadState
{
Success = 0,
SizeLimitExceed = -1,
TypeNotAllow = -2,
FileAccessError = -3,
NetworkError = -4,
Unknown = 1,
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.AspNetCore.Http;
namespace UEditor.Core.Handlers
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class UploadHandler : Handler
{
public UploadConfig UploadConfig { get; set; }
public UploadResult Result { get; private set; }
public UploadHandler(HttpContext context)
: base(context)
{
this.Result = new UploadResult() { State = UploadState.Unknown };
}
public override UEditorResult Process()
{
byte[] uploadFileBytes = null;
string uploadFileName = null;
if (UploadConfig.Base64)
{
uploadFileName = UploadConfig.Base64Filename;
uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]);
}
else
{
var file = Request.Form.Files[UploadConfig.UploadFieldName];
uploadFileName = file.FileName;
if (!CheckFileType(uploadFileName))
{
Result.State = UploadState.TypeNotAllow;
return WriteResult();
}
if (!CheckFileSize(file.Length))
{
Result.State = UploadState.SizeLimitExceed;
return WriteResult();
}
uploadFileBytes = new byte[file.Length];
try
{
file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length);
}
catch (Exception)
{
Result.State = UploadState.NetworkError;
WriteResult();
}
}
Result.OriginFileName = uploadFileName;
var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
var localPath = Path.Combine(Config.WebRootPath,savePath);
UEditorResult result;
try
{
if (!Directory.Exists(Path.GetDirectoryName(localPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(localPath));
}
File.WriteAllBytes(localPath, uploadFileBytes);
Result.Url =savePath;
Result.State = UploadState.Success;
}
catch (Exception e)
{
Result.State = UploadState.FileAccessError;
Result.ErrorMessage = e.Message;
}
finally
{
result = WriteResult();
}
return result;
}
private UEditorResult WriteResult()
{
return new UEditorResult
{
State = GetStateMessage(Result.State),
Url = Result.Url,
Title = Result.OriginFileName,
Original = Result.OriginFileName,
Error = Result.ErrorMessage
};
}
private string GetStateMessage(UploadState state)
{
switch (state)
{
case UploadState.Success:
return "SUCCESS";
case UploadState.FileAccessError:
return "文件访问出错,请检查写入权限";
case UploadState.SizeLimitExceed:
return "文件大小超出服务器限制";
case UploadState.TypeNotAllow:
return "不允许的文件格式";
case UploadState.NetworkError:
return "网络错误";
}
return "未知错误";
}
private bool CheckFileType(string filename)
{
var fileExtension = Path.GetExtension(filename).ToLower();
return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
}
private bool CheckFileSize(long size)
{
return size < UploadConfig.SizeLimit;
}
}
public class UploadConfig
{
/// <summary>
/// 文件命名规则
/// </summary>
public string PathFormat { get; set; }
/// <summary>
/// 上传表单域名称
/// </summary>
public string UploadFieldName { get; set; }
/// <summary>
/// 上传大小限制
/// </summary>
public int SizeLimit { get; set; }
/// <summary>
/// 上传允许的文件格式
/// </summary>
public string[] AllowExtensions { get; set; }
/// <summary>
/// 文件是否以 Base64 的形式上传
/// </summary>
public bool Base64 { get; set; }
/// <summary>
/// Base64 字符串所表示的文件名
/// </summary>
public string Base64Filename { get; set; }
}
public class UploadResult
{
public UploadState State { get; set; }
public string Url { get; set; }
public string OriginFileName { get; set; }
public string ErrorMessage { get; set; }
}
public enum UploadState
{
Success = 0,
SizeLimitExceed = -1,
TypeNotAllow = -2,
FileAccessError = -3,
NetworkError = -4,
Unknown = 1,
}
}