UploadHandler.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using System.Web;
  7. /// <summary>
  8. /// UploadHandler 的摘要说明
  9. /// </summary>
  10. public class UploadHandler : Handler
  11. {
  12. public UploadConfig UploadConfig { get; private set; }
  13. public UploadResult Result { get; private set; }
  14. public UploadHandler(HttpContext context, UploadConfig config)
  15. : base(context)
  16. {
  17. this.UploadConfig = config;
  18. this.Result = new UploadResult() { State = UploadState.Unknown };
  19. }
  20. public override void Process()
  21. {
  22. byte[] uploadFileBytes = null;
  23. string uploadFileName = null;
  24. if (UploadConfig.Base64)
  25. {
  26. uploadFileName = UploadConfig.Base64Filename;
  27. uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
  28. }
  29. else
  30. {
  31. var file = Request.Files[UploadConfig.UploadFieldName];
  32. uploadFileName = file.FileName;
  33. if (!CheckFileType(uploadFileName))
  34. {
  35. Result.State = UploadState.TypeNotAllow;
  36. WriteResult();
  37. return;
  38. }
  39. if (!CheckFileSize(file.ContentLength))
  40. {
  41. Result.State = UploadState.SizeLimitExceed;
  42. WriteResult();
  43. return;
  44. }
  45. uploadFileBytes = new byte[file.ContentLength];
  46. try
  47. {
  48. file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
  49. }
  50. catch (Exception)
  51. {
  52. Result.State = UploadState.NetworkError;
  53. WriteResult();
  54. }
  55. }
  56. Result.OriginFileName = uploadFileName;
  57. var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
  58. var localPath = Server.MapPath(savePath);
  59. try
  60. {
  61. if (!Directory.Exists(Path.GetDirectoryName(localPath)))
  62. {
  63. Directory.CreateDirectory(Path.GetDirectoryName(localPath));
  64. }
  65. File.WriteAllBytes(localPath, uploadFileBytes);
  66. Result.Url = savePath;
  67. Result.State = UploadState.Success;
  68. }
  69. catch (Exception e)
  70. {
  71. Result.State = UploadState.FileAccessError;
  72. Result.ErrorMessage = e.Message;
  73. }
  74. finally
  75. {
  76. WriteResult();
  77. }
  78. }
  79. private void WriteResult()
  80. {
  81. this.WriteJson(new
  82. {
  83. state = GetStateMessage(Result.State),
  84. url = Result.Url,
  85. title = Result.OriginFileName,
  86. original = Result.OriginFileName,
  87. error = Result.ErrorMessage
  88. });
  89. }
  90. private string GetStateMessage(UploadState state)
  91. {
  92. switch (state)
  93. {
  94. case UploadState.Success:
  95. return "SUCCESS";
  96. case UploadState.FileAccessError:
  97. return "文件访问出错,请检查写入权限";
  98. case UploadState.SizeLimitExceed:
  99. return "文件大小超出服务器限制";
  100. case UploadState.TypeNotAllow:
  101. return "不允许的文件格式";
  102. case UploadState.NetworkError:
  103. return "网络错误";
  104. }
  105. return "未知错误";
  106. }
  107. private bool CheckFileType(string filename)
  108. {
  109. var fileExtension = Path.GetExtension(filename).ToLower();
  110. return UploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension);
  111. }
  112. private bool CheckFileSize(int size)
  113. {
  114. return size < UploadConfig.SizeLimit;
  115. }
  116. }
  117. public class UploadConfig
  118. {
  119. /// <summary>
  120. /// 文件命名规则
  121. /// </summary>
  122. public string PathFormat { get; set; }
  123. /// <summary>
  124. /// 上传表单域名称
  125. /// </summary>
  126. public string UploadFieldName { get; set; }
  127. /// <summary>
  128. /// 上传大小限制
  129. /// </summary>
  130. public int SizeLimit { get; set; }
  131. /// <summary>
  132. /// 上传允许的文件格式
  133. /// </summary>
  134. public string[] AllowExtensions { get; set; }
  135. /// <summary>
  136. /// 文件是否以 Base64 的形式上传
  137. /// </summary>
  138. public bool Base64 { get; set; }
  139. /// <summary>
  140. /// Base64 字符串所表示的文件名
  141. /// </summary>
  142. public string Base64Filename { get; set; }
  143. }
  144. public class UploadResult
  145. {
  146. public UploadState State { get; set; }
  147. public string Url { get; set; }
  148. public string OriginFileName { get; set; }
  149. public string ErrorMessage { get; set; }
  150. }
  151. public enum UploadState
  152. {
  153. Success = 0,
  154. SizeLimitExceed = -1,
  155. TypeNotAllow = -2,
  156. FileAccessError = -3,
  157. NetworkError = -4,
  158. Unknown = 1,
  159. }