UploadController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. using DocumentFormat.OpenXml.Packaging;
  2. using HtmlAgilityPack;
  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.AspNetCore.Mime;
  8. using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions;
  9. using Masuit.Tools.Core.Net;
  10. using Masuit.Tools.Html;
  11. using Masuit.Tools.Logging;
  12. using Masuit.Tools.Systems;
  13. using Microsoft.AspNetCore.Hosting;
  14. using Microsoft.AspNetCore.Http;
  15. using Microsoft.AspNetCore.Mvc;
  16. using Newtonsoft.Json;
  17. using OpenXmlPowerTools;
  18. using System;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Text;
  22. using System.Text.RegularExpressions;
  23. using System.Threading.Tasks;
  24. using System.Xml.Linq;
  25. namespace Masuit.MyBlogs.Core.Controllers
  26. {
  27. /// <summary>
  28. /// 文件上传
  29. /// </summary>
  30. [ApiExplorerSettings(IgnoreApi = true)]
  31. public class UploadController : Controller
  32. {
  33. public IWebHostEnvironment HostEnvironment { get; set; }
  34. public ImagebedClient ImagebedClient { get; set; }
  35. /// <summary>
  36. ///
  37. /// </summary>
  38. /// <param name="data"></param>
  39. /// <param name="isTrue"></param>
  40. /// <param name="message"></param>
  41. /// <returns></returns>
  42. public ActionResult ResultData(object data, bool isTrue = true, string message = "")
  43. {
  44. return Content(JsonConvert.SerializeObject(new
  45. {
  46. Success = isTrue,
  47. Message = message,
  48. Data = data
  49. }, new JsonSerializerSettings
  50. {
  51. MissingMemberHandling = MissingMemberHandling.Ignore
  52. }), "application/json", Encoding.UTF8);
  53. }
  54. #region Word上传转码
  55. /// <summary>
  56. /// 上传Word转码
  57. /// </summary>
  58. /// <returns></returns>
  59. [HttpPost]
  60. public async Task<ActionResult> UploadWord()
  61. {
  62. var files = Request.Form.Files;
  63. if (files.Count <= 0)
  64. {
  65. return ResultData(null, false, "请先选择您需要上传的文件!");
  66. }
  67. var file = files[0];
  68. string fileName = file.FileName;
  69. if (!Regex.IsMatch(Path.GetExtension(fileName), "doc|docx"))
  70. {
  71. return ResultData(null, false, "文件格式不支持,只能上传doc或者docx的文档!");
  72. }
  73. var html = await SaveAsHtml(file);
  74. if (html.Length < 10)
  75. {
  76. return ResultData(null, false, "读取文件内容失败,请检查文件的完整性,建议另存后重新上传!");
  77. }
  78. if (html.Length > 1000000)
  79. {
  80. return ResultData(null, false, "文档内容超长,服务器拒绝接收,请优化文档内容后再尝试重新上传!");
  81. }
  82. return ResultData(new
  83. {
  84. Title = Path.GetFileNameWithoutExtension(fileName),
  85. Content = html
  86. });
  87. }
  88. private string ConvertToHtml(IFormFile file)
  89. {
  90. using var ms = file.OpenReadStream();
  91. using var fs = new FileStream(Path.Combine(Environment.GetEnvironmentVariable("temp") ??
  92. "upload", file.FileName), FileMode.OpenOrCreate, FileAccess.ReadWrite);
  93. ms.CopyTo(fs);
  94. using var doc = WordprocessingDocument.Open(fs, true);
  95. var pageTitle = file.FileName;
  96. var part = doc.CoreFilePropertiesPart;
  97. if (part != null)
  98. {
  99. pageTitle ??= (string)part.GetXDocument().Descendants(DC.title).FirstOrDefault();
  100. }
  101. var settings = new HtmlConverterSettings()
  102. {
  103. PageTitle = pageTitle,
  104. FabricateCssClasses = false,
  105. RestrictToSupportedLanguages = false,
  106. RestrictToSupportedNumberingFormats = false,
  107. ImageHandler = imageInfo =>
  108. {
  109. var stream = new MemoryStream();
  110. imageInfo.Bitmap.Save(stream, imageInfo.Bitmap.RawFormat);
  111. var base64String = Convert.ToBase64String(stream.ToArray());
  112. return new XElement(Xhtml.img, new XAttribute(NoNamespace.src, $"data:{imageInfo.ContentType};base64," + base64String), imageInfo.ImgStyleAttribute, imageInfo.AltText != null ? new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
  113. }
  114. };
  115. var htmlElement = HtmlConverter.ConvertToHtml(doc, settings);
  116. var html = new XDocument(new XDocumentType("html", null, null, null), htmlElement);
  117. var htmlString = html.ToString(SaveOptions.DisableFormatting);
  118. return htmlString;
  119. }
  120. private async Task<string> SaveAsHtml(IFormFile file)
  121. {
  122. var html = ConvertToHtml(file);
  123. var doc = new HtmlDocument();
  124. doc.LoadHtml(html);
  125. var body = doc.DocumentNode.SelectSingleNode("//body");
  126. var style = doc.DocumentNode.SelectSingleNode("//style");
  127. var nodes = body.SelectNodes("//img");
  128. if (nodes != null)
  129. {
  130. foreach (var img in nodes)
  131. {
  132. var attr = img.Attributes["src"].Value;
  133. var strs = attr.Split(",");
  134. var base64 = strs[1];
  135. var bytes = Convert.FromBase64String(base64);
  136. var ext = strs[0].Split(";")[0].Split("/")[1];
  137. await using var image = new MemoryStream(bytes);
  138. var imgFile = $"{SnowFlake.NewId}.{ext}";
  139. var (url, success) = await ImagebedClient.UploadImage(image, imgFile);
  140. if (success)
  141. {
  142. img.Attributes["src"].Value = url;
  143. }
  144. else
  145. {
  146. var path = Path.Combine(HostEnvironment.WebRootPath, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\'), "images", imgFile);
  147. await SaveFile(file, path);
  148. img.Attributes["src"].Value = path.Substring(HostEnvironment.WebRootPath.Length).Replace("\\", "/");
  149. }
  150. }
  151. }
  152. return style.OuterHtml + body.InnerHtml.HtmlSantinizerStandard().HtmlSantinizerCustom(attributes: new[] { "dir", "lang" });
  153. }
  154. private static async Task SaveFile(IFormFile file, string path)
  155. {
  156. var dir = Path.GetDirectoryName(path);
  157. if (!Directory.Exists(dir))
  158. {
  159. Directory.CreateDirectory(dir);
  160. }
  161. await using var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  162. await file.CopyToAsync(fs);
  163. }
  164. #endregion
  165. /// <summary>
  166. /// 文件下载
  167. /// </summary>
  168. /// <param name="path"></param>
  169. /// <returns></returns>
  170. [Route("download")]
  171. [Route("download/{path}")]
  172. public ActionResult Download(string path)
  173. {
  174. if (string.IsNullOrEmpty(path)) return Content("null");
  175. var file = Path.Combine(HostEnvironment.WebRootPath, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\'), path.Trim('.', '/', '\\'));
  176. if (System.IO.File.Exists(file))
  177. {
  178. return this.ResumePhysicalFile(file, Path.GetFileName(file));
  179. }
  180. return Content("null");
  181. }
  182. /// <summary>
  183. /// UEditor文件上传处理
  184. /// </summary>
  185. /// <returns></returns>
  186. [Route("fileuploader")]
  187. public ActionResult UeditorFileUploader()
  188. {
  189. UserInfoDto user = HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
  190. var action = Request.Query["action"].ToString() switch //通用
  191. {
  192. "config" => (Handler)new ConfigHandler(HttpContext),
  193. "uploadimage" => new UploadHandler(HttpContext, new UploadConfig()
  194. {
  195. AllowExtensions = UeditorConfig.GetStringList("imageAllowFiles"),
  196. PathFormat = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\') + UeditorConfig.GetString("imagePathFormat"),
  197. SizeLimit = UeditorConfig.GetInt("imageMaxSize"),
  198. UploadFieldName = UeditorConfig.GetString("imageFieldName")
  199. }),
  200. "uploadscrawl" => new UploadHandler(HttpContext, new UploadConfig()
  201. {
  202. AllowExtensions = new[]
  203. {
  204. ".png"
  205. },
  206. PathFormat = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\') + UeditorConfig.GetString("scrawlPathFormat"),
  207. SizeLimit = UeditorConfig.GetInt("scrawlMaxSize"),
  208. UploadFieldName = UeditorConfig.GetString("scrawlFieldName"),
  209. Base64 = true,
  210. Base64Filename = "scrawl.png"
  211. }),
  212. "catchimage" => new CrawlerHandler(HttpContext),
  213. _ => new NotSupportedHandler(HttpContext)
  214. };
  215. if (user.IsAdmin)
  216. {
  217. switch (Request.Query["action"])//管理员用
  218. {
  219. //case "uploadvideo":
  220. // action = new UploadHandler(context, new UploadConfig()
  221. // {
  222. // AllowExtensions = UeditorConfig.GetStringList("videoAllowFiles"),
  223. // PathFormat = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload") + UeditorConfig.GetString("videoPathFormat"),
  224. // SizeLimit = UeditorConfig.GetInt("videoMaxSize"),
  225. // UploadFieldName = UeditorConfig.GetString("videoFieldName")
  226. // });
  227. // break;
  228. case "uploadfile":
  229. action = new UploadHandler(HttpContext, new UploadConfig()
  230. {
  231. AllowExtensions = UeditorConfig.GetStringList("fileAllowFiles"),
  232. PathFormat = "/" + CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\') + UeditorConfig.GetString("filePathFormat"),
  233. SizeLimit = UeditorConfig.GetInt("fileMaxSize"),
  234. UploadFieldName = UeditorConfig.GetString("fileFieldName")
  235. });
  236. break;
  237. //case "listimage":
  238. // action = new ListFileManager(context, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "/upload") + UeditorConfig.GetString("imageManagerListPath"), UeditorConfig.GetStringList("imageManagerAllowFiles"));
  239. // break;
  240. //case "listfile":
  241. // action = new ListFileManager(context, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "/upload") + UeditorConfig.GetString("fileManagerListPath"), UeditorConfig.GetStringList("fileManagerAllowFiles"));
  242. // break;
  243. }
  244. }
  245. string result = action.Process();
  246. return Content(result, ContentType.Json);
  247. }
  248. /// <summary>
  249. /// 上传文件
  250. /// </summary>
  251. /// <param name="file"></param>
  252. /// <returns></returns>
  253. [HttpPost("upload"), ApiExplorerSettings(IgnoreApi = false)]
  254. public async Task<ActionResult> UploadFile(IFormFile file)
  255. {
  256. string path;
  257. string filename = SnowFlake.GetInstance().GetUniqueId() + Path.GetExtension(file.FileName);
  258. switch (file.ContentType)
  259. {
  260. case var _ when file.ContentType.StartsWith("image"):
  261. {
  262. var (url, success) = await ImagebedClient.UploadImage(file.OpenReadStream(), file.FileName);
  263. if (success)
  264. {
  265. return ResultData(url);
  266. }
  267. path = Path.Combine(HostEnvironment.WebRootPath, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\'), "images", filename);
  268. var dir = Path.GetDirectoryName(path);
  269. if (!Directory.Exists(dir))
  270. {
  271. Directory.CreateDirectory(dir);
  272. }
  273. await using var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  274. await file.CopyToAsync(fs);
  275. break;
  276. }
  277. case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
  278. path = Path.Combine(HostEnvironment.WebRootPath, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\'), "media", filename);
  279. break;
  280. case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
  281. path = Path.Combine(HostEnvironment.WebRootPath, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\'), "docs", filename);
  282. break;
  283. default:
  284. path = Path.Combine(HostEnvironment.WebRootPath, CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\'), "files", filename);
  285. break;
  286. }
  287. try
  288. {
  289. await SaveFile(file, path);
  290. return ResultData(path.Substring(HostEnvironment.WebRootPath.Length).Replace("\\", "/"));
  291. }
  292. catch (Exception e)
  293. {
  294. LogManager.Error(e);
  295. return ResultData(null, false, "文件上传失败!");
  296. }
  297. }
  298. }
  299. }