UploadController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using Common;
  2. using Hangfire;
  3. using Masuit.MyBlogs.Core.Common;
  4. using Masuit.MyBlogs.Core.Extensions.UEditor;
  5. using Masuit.MyBlogs.Core.Models.DTO;
  6. using Masuit.MyBlogs.Core.Models.ViewModel;
  7. using Masuit.Tools;
  8. using Masuit.Tools.AspNetCore.Mime;
  9. using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
  10. using Masuit.Tools.Core.Net;
  11. using Masuit.Tools.Html;
  12. using Masuit.Tools.Logging;
  13. using Masuit.Tools.Systems;
  14. using Microsoft.AspNetCore.Hosting;
  15. using Microsoft.AspNetCore.Http;
  16. using Microsoft.AspNetCore.Mvc;
  17. using Newtonsoft.Json;
  18. using System;
  19. using System.IO;
  20. using System.Text;
  21. using System.Text.RegularExpressions;
  22. using System.Threading;
  23. namespace Masuit.MyBlogs.Core.Controllers
  24. {
  25. /// <summary>
  26. /// 文件上传
  27. /// </summary>
  28. [ApiExplorerSettings(IgnoreApi = true)]
  29. public class UploadController : Controller
  30. {
  31. private readonly IHostingEnvironment _hostingEnvironment;
  32. /// <summary>
  33. /// 文件上传
  34. /// </summary>
  35. /// <param name="hostingEnvironment"></param>
  36. public UploadController(IHostingEnvironment hostingEnvironment)
  37. {
  38. _hostingEnvironment = hostingEnvironment;
  39. }
  40. /// <summary>
  41. ///
  42. /// </summary>
  43. /// <param name="data"></param>
  44. /// <param name="isTrue"></param>
  45. /// <param name="message"></param>
  46. /// <returns></returns>
  47. public ActionResult ResultData(object data, bool isTrue = true, string message = "")
  48. {
  49. return Content(JsonConvert.SerializeObject(new
  50. {
  51. Success = isTrue,
  52. Message = message,
  53. Data = data
  54. }, new JsonSerializerSettings
  55. {
  56. MissingMemberHandling = MissingMemberHandling.Ignore
  57. }), "application/json", Encoding.UTF8);
  58. }
  59. #region Word上传转码
  60. /// <summary>
  61. /// 上传Word转码
  62. /// </summary>
  63. /// <returns></returns>
  64. [HttpPost]
  65. public ActionResult UploadWord()
  66. {
  67. var files = Request.Form.Files;
  68. if (files.Count > 0 && files[0] != null)
  69. {
  70. var file = files[0];
  71. string fileName = file.FileName;
  72. if (fileName != null && !Regex.IsMatch(Path.GetExtension(fileName), "doc|docx"))
  73. {
  74. return ResultData(null, false, "文件格式不支持,只能上传doc或者docx的文档!");
  75. }
  76. if (fileName != null)
  77. {
  78. string upload = _hostingEnvironment.WebRootPath + "/upload";
  79. if (!Directory.Exists(upload))
  80. {
  81. Directory.CreateDirectory(upload);
  82. }
  83. string resourceName = string.Empty.CreateShortToken(9);
  84. string ext = Path.GetExtension(fileName);
  85. string docPath = Path.Combine(upload, resourceName + ext);
  86. using (FileStream fs = new FileStream(docPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  87. {
  88. file.CopyTo(fs);
  89. }
  90. string htmlDir = docPath.Replace(".docx", "").Replace(".doc", "");
  91. DocumentConvert.Doc2Html(docPath, htmlDir);
  92. string htmlfile = Path.Combine(htmlDir, "index.html");
  93. string html = System.IO.File.ReadAllText(htmlfile).ReplaceHtmlImgSource("/upload/" + resourceName).ClearHtml().HtmlSantinizerStandard();
  94. ThreadPool.QueueUserWorkItem(state => System.IO.File.Delete(htmlfile));
  95. if (html.Length < 10)
  96. {
  97. Directory.Delete(htmlDir, true);
  98. System.IO.File.Delete(docPath);
  99. return ResultData(null, false, "读取文件内容失败,请检查文件的完整性,建议另存后重新上传!");
  100. }
  101. if (html.Length > 1000000)
  102. {
  103. Directory.Delete(htmlDir, true);
  104. System.IO.File.Delete(docPath);
  105. return ResultData(null, false, "文档内容超长,服务器拒绝接收,请优化文档内容后再尝试重新上传!");
  106. }
  107. return ResultData(new
  108. {
  109. Title = Path.GetFileNameWithoutExtension(fileName),
  110. Content = html,
  111. ResourceName = resourceName + ext
  112. });
  113. }
  114. }
  115. return ResultData(null, false, "请先选择您需要上传的文件!");
  116. }
  117. ///// <summary>
  118. ///// 解码Base64图片
  119. ///// </summary>
  120. ///// <param name="data"></param>
  121. ///// <returns></returns>
  122. //public ActionResult DecodeDataUri(string data)
  123. //{
  124. // var filename = string.Empty.CreateShortToken() + ".jpg";
  125. // string path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "images", filename);
  126. // try
  127. // {
  128. // data.SaveDataUriAsImageFile().Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
  129. // var (url, success) = CommonHelper.UploadImage(path);
  130. // BackgroundJob.Enqueue(() => System.IO.File.Delete(path));
  131. // if (success)
  132. // {
  133. // return ResultData(url);
  134. // }
  135. // return ResultData(null, false, "图片上传失败!");
  136. // }
  137. // catch (Exception e)
  138. // {
  139. // LogManager.Error(e);
  140. // return ResultData(null, false, "转码失败!");
  141. // }
  142. //}
  143. #endregion
  144. /// <summary>
  145. /// 文件下载
  146. /// </summary>
  147. /// <param name="path"></param>
  148. /// <returns></returns>
  149. [Route("download")]
  150. [Route("download/{path}")]
  151. public ActionResult Download(string path)
  152. {
  153. if (string.IsNullOrEmpty(path)) return Content("null");
  154. var file = Path.Combine(_hostingEnvironment.WebRootPath + "/upload", path.Trim('.', '/', '\\'));
  155. if (System.IO.File.Exists(file))
  156. {
  157. return this.ResumePhysicalFile(file, Path.GetFileName(file));
  158. }
  159. return Content("null");
  160. }
  161. /// <summary>
  162. /// UEditor文件上传处理
  163. /// </summary>
  164. /// <returns></returns>
  165. [Route("fileuploader")]
  166. public ActionResult UeditorFileUploader()
  167. {
  168. UserInfoOutputDto user = HttpContext.Session.Get<UserInfoOutputDto>(SessionKey.UserInfo) ?? new UserInfoOutputDto();
  169. Handler action = new NotSupportedHandler(HttpContext);
  170. switch (Request.Query["action"])//通用
  171. {
  172. case "config":
  173. action = new ConfigHandler(HttpContext);
  174. break;
  175. case "uploadimage":
  176. action = new UploadHandler(HttpContext, new UploadConfig()
  177. {
  178. AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
  179. PathFormat = UeditorConfig.GetString("imagePathFormat"),
  180. SizeLimit = UeditorConfig.GetInt("imageMaxSize"),
  181. UploadFieldName = UeditorConfig.GetString("imageFieldName")
  182. });
  183. break;
  184. case "uploadscrawl":
  185. action = new UploadHandler(HttpContext, new UploadConfig()
  186. {
  187. AllowExtensions = new[] { ".png" },
  188. PathFormat = UeditorConfig.GetString("scrawlPathFormat"),
  189. SizeLimit = UeditorConfig.GetInt("scrawlMaxSize"),
  190. UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
  191. Base64 = true,
  192. Base64Filename = "scrawl.png"
  193. });
  194. break;
  195. case "catchimage":
  196. action = new CrawlerHandler(HttpContext);
  197. break;
  198. }
  199. if (user.IsAdmin)
  200. {
  201. switch (Request.Query["action"])//管理员用
  202. {
  203. //case "uploadvideo":
  204. // action = new UploadHandler(context, new UploadConfig()
  205. // {
  206. // AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
  207. // PathFormat = UeditorConfig.GetString("videoPathFormat"),
  208. // SizeLimit = UeditorConfig.GetInt("videoMaxSize"),
  209. // UploadFieldName = UeditorConfig.GetString("videoFieldName")
  210. // });
  211. // break;
  212. case "uploadfile":
  213. action = new UploadHandler(HttpContext, new UploadConfig()
  214. {
  215. AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
  216. PathFormat = UeditorConfig.GetString("filePathFormat"),
  217. SizeLimit = UeditorConfig.GetInt("fileMaxSize"),
  218. UploadFieldName = UeditorConfig.GetString("fileFieldName")
  219. });
  220. break;
  221. //case "listimage":
  222. // action = new ListFileManager(context, UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
  223. // break;
  224. //case "listfile":
  225. // action = new ListFileManager(context, UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
  226. // break;
  227. }
  228. }
  229. string result = action.Process();
  230. return Content(result, ContentType.Json);
  231. }
  232. /// <summary>
  233. /// 上传文件
  234. /// </summary>
  235. /// <param name="file"></param>
  236. /// <returns></returns>
  237. [HttpPost("upload"), ApiExplorerSettings(IgnoreApi = false)]
  238. public ActionResult UploadFile(IFormFile file)
  239. {
  240. string path;
  241. string filename = SnowFlake.GetInstance().GetUniqueId() + Path.GetExtension(file.FileName);
  242. switch (file.ContentType)
  243. {
  244. case var _ when file.ContentType.StartsWith("image"):
  245. path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "images", filename);
  246. var dir = Path.GetDirectoryName(path);
  247. if (!Directory.Exists(dir))
  248. {
  249. Directory.CreateDirectory(dir);
  250. }
  251. using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  252. {
  253. file.CopyTo(fs);
  254. }
  255. var (url, success) = CommonHelper.UploadImage(path);
  256. if (success)
  257. {
  258. BackgroundJob.Enqueue(() => System.IO.File.Delete(path));
  259. return ResultData(url);
  260. }
  261. break;
  262. case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
  263. path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "media", filename);
  264. break;
  265. case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
  266. path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "docs", filename);
  267. break;
  268. default:
  269. path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "files", filename);
  270. break;
  271. }
  272. try
  273. {
  274. var dir = Path.GetDirectoryName(path);
  275. if (!Directory.Exists(dir))
  276. {
  277. Directory.CreateDirectory(dir);
  278. }
  279. using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  280. {
  281. file.CopyTo(fs);
  282. }
  283. return ResultData(path.Substring(_hostingEnvironment.WebRootPath.Length).Replace("\\", "/"));
  284. }
  285. catch (Exception e)
  286. {
  287. LogManager.Error(e);
  288. return ResultData(null, false, "文件上传失败!");
  289. }
  290. }
  291. }
  292. }