UploadFileHelper.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. using System;
  2. using System.Collections;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Web;
  6. namespace CommonTool
  7. {
  8. public class UploadFileHelper
  9. {
  10. public static UploadFileHelper Instance { get; } = new UploadFileHelper();
  11. public UploadResult UploadFiles(string filePath, string fileType, HttpRequestBase request,HttpServerUtilityBase server)
  12. {
  13. UploadResult result = new UploadResult
  14. {
  15. FileUrls = new ArrayList(),
  16. Success = false,
  17. Msg = "Failure!",
  18. VirtualPathUrls = new ArrayList(),
  19. };
  20. //遍历所有文件域
  21. foreach (string fieldName in request.Files.AllKeys)
  22. {
  23. HttpPostedFileBase file = request.Files.Get(fieldName);
  24. string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
  25. filePath += ymd + "/";
  26. string fileName = DateTime.Now.ToString("yyyyMMddhhmmss_ffff");
  27. string urlPath = $"{filePath}{fileName}.{fileType}";
  28. string virtualPath= server.MapPath(urlPath);
  29. try
  30. {
  31. if (!Directory.Exists(server.MapPath(filePath)))
  32. Directory.CreateDirectory(server.MapPath(filePath));
  33. file?.SaveAs(virtualPath);
  34. result.FileUrls.Add(urlPath);
  35. result.VirtualPathUrls.Add(virtualPath);
  36. result.Success = true;
  37. result.Msg = "Success!";
  38. }
  39. catch (Exception e)
  40. {
  41. result.Msg = e.Message;
  42. return result;
  43. }
  44. }
  45. return result;
  46. }
  47. public UploadResult UploadFiles2(string filePath, HttpPostedFileBase requestFile, HttpServerUtilityBase server)
  48. {
  49. UploadResult result = new UploadResult
  50. {
  51. FileUrls = new ArrayList(),
  52. Success = false,
  53. Msg = "Failure!"
  54. };
  55. //遍历所有文件域
  56. string urlPath = $"{filePath}";
  57. string virtualPath = server.MapPath(urlPath);
  58. try
  59. {
  60. if (File.Exists(virtualPath))
  61. File.Delete(virtualPath);
  62. requestFile?.SaveAs(virtualPath);
  63. result.FileUrls.Add(urlPath);
  64. result.VirtualPathUrls.Add(virtualPath);
  65. result.Success = true;
  66. result.Msg = "Success!";
  67. }
  68. catch (Exception e)
  69. {
  70. result.Msg = e.Message;
  71. return result;
  72. }
  73. return result;
  74. }
  75. }
  76. public class UploadResult
  77. {
  78. /// <summary>
  79. /// 表示文件是否已上传成功。
  80. /// </summary>
  81. // ReSharper disable once InconsistentNaming
  82. public bool Success;
  83. /// <summary>
  84. /// 自定义的附加消息。
  85. /// </summary>
  86. // ReSharper disable once InconsistentNaming
  87. public string Msg;
  88. /// <summary>
  89. /// 表示所有文件的保存地址,该变量为一个数组。
  90. /// </summary>
  91. // ReSharper disable once InconsistentNaming
  92. public ArrayList FileUrls;
  93. public ArrayList VirtualPathUrls;
  94. }
  95. public class UploadKindEditor
  96. {
  97. public static UploadKindEditor Instance { get; } = new UploadKindEditor();
  98. public HttpContextBase Context { get; set; }
  99. public string KindEditorUpload(string filePath, HttpContextBase context)
  100. {
  101. Context = context;
  102. string dirPath = filePath;//文件保存目录路径
  103. int maxSize = 10*1024*1024;//最大文件大小
  104. string dirName = context.Request.QueryString["dir"];
  105. string fileUrl;
  106. //定义允许上传的文件扩展名
  107. Hashtable extTable = new Hashtable
  108. {
  109. {"image", "gif,jpg,jpeg,png,bmp"},
  110. {"flash", "swf,flv"},
  111. {"media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"},
  112. {"file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"}
  113. };
  114. HttpPostedFileBase imgFile = context.Request.Files["imgFile"];
  115. //if (!Directory.Exists(dirPath))
  116. //{
  117. // showError("上传目录不存在。");
  118. //}
  119. if (string.IsNullOrEmpty(dirName))
  120. {
  121. dirName = "image";
  122. }
  123. if (!extTable.ContainsKey(dirName))
  124. {
  125. return showError("目录名不正确。");
  126. }
  127. if (imgFile == null)
  128. {
  129. return showError("请选择文件。");
  130. }
  131. string fileName = imgFile.FileName;
  132. string fileExt = Path.GetExtension(fileName)?.ToLower();
  133. if (imgFile.InputStream.Length > maxSize)
  134. {
  135. return showError("上传文件大小超过限制。");
  136. }
  137. if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((string)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
  138. {
  139. return showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
  140. }
  141. //创建文件夹
  142. dirPath += dirName + "/";
  143. var savePath = context.Server.MapPath(dirPath);
  144. if (!Directory.Exists(savePath))
  145. {
  146. Directory.CreateDirectory(savePath);
  147. }
  148. string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
  149. dirPath += ymd + "/";
  150. savePath = context.Server.MapPath(dirPath);
  151. if (!Directory.Exists(savePath))
  152. {
  153. Directory.CreateDirectory(savePath);
  154. }
  155. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
  156. filePath = savePath + newFileName;
  157. imgFile.SaveAs(filePath);
  158. fileUrl = dirPath + newFileName;
  159. Hashtable hash = new Hashtable
  160. {
  161. ["error"] = 0,
  162. ["url"] = fileUrl
  163. };
  164. return hash.ToJson();
  165. }
  166. private string showError(string message)
  167. {
  168. Hashtable hash = new Hashtable
  169. {
  170. ["error"] = 1,
  171. ["message"] = message
  172. };
  173. return hash.ToJson();
  174. }
  175. }
  176. }