PublicMethodController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Http;
  5. using System.DrawingCore.Imaging;
  6. using System.IO;
  7. using Library;
  8. using System.Collections;
  9. using LitJson;
  10. using System.Globalization;
  11. using System.Web;
  12. using System.Security.Cryptography;
  13. using System.Text;
  14. using Aliyun.OSS;
  15. namespace MySystem.Areas.Api.Controllers
  16. {
  17. [Area("Api")]
  18. [Route("Api/[controller]/[action]")]
  19. public class PublicMethodController : BaseController
  20. {
  21. public PublicMethodController(IHttpContextAccessor accessor) : base(accessor)
  22. {
  23. }
  24. #region 图片验证码
  25. public FileContentResult CheckCode()
  26. {
  27. string code = function.get_Random(4);
  28. var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 120, 40);
  29. MemoryStream stream = new MemoryStream();
  30. bitmap.Save(stream, ImageFormat.Gif);
  31. function.WriteCookie(_accessor.HttpContext, "checkcode", code);
  32. return File(stream.ToArray(), "image/gif");
  33. }
  34. #endregion
  35. #region 图片验证码
  36. public FileContentResult PictureCode(string Tag = "")
  37. {
  38. string code = function.get_Random(4);
  39. var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 120, 40);
  40. MemoryStream stream = new MemoryStream();
  41. bitmap.Save(stream, ImageFormat.Gif);
  42. RedisDbconn.Instance.Set(Tag, code);
  43. RedisDbconn.Instance.SetExpire(Tag, 600);
  44. return File(stream.ToArray(), "image/jpg");
  45. }
  46. #endregion
  47. #region 前端上传oss返回参数
  48. public JsonResult OssInfo(string value)
  49. {
  50. value = DesDecrypt(value);
  51. JsonData data = JsonMapper.ToObject(value);
  52. string dir = data["dir"].ToString(); //文件上传路径
  53. if (string.IsNullOrEmpty(data["dir"].ToString()))
  54. {
  55. return Json(new AppResultJson() { Status = "1", Info = "文件上传路径不能为空" });
  56. }
  57. Dictionary<string, object> Obj = new Dictionary<string, object>();
  58. var OssUrl = OssHost;
  59. var AccessKeyId = OssKey;
  60. var AccessKeySecret = OssSecret;
  61. var endpoint = "https://" + OssEndpoint;
  62. // 构造OssClient实例。 endpoint 格式:https://oss-cn-beijing.aliyuncs.com
  63. var ossClient = new OssClient(endpoint, AccessKeyId, AccessKeySecret);
  64. var config = new PolicyConditions();
  65. config.AddConditionItem(PolicyConditions.CondContentLengthRange, 1, 1024L * 1024 * 1024 * 5);// 文件大小范围:单位byte
  66. config.AddConditionItem(MatchMode.StartWith, PolicyConditions.CondKey, dir);
  67. var expire = DateTimeOffset.Now.AddMinutes(30);// 过期时间
  68. // 生成 Policy,并进行 Base64 编码
  69. var policy = ossClient.GeneratePostPolicy(expire.LocalDateTime, config);
  70. var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));
  71. // 计算签名
  72. var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(AccessKeySecret));
  73. var bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(policyBase64));
  74. var Signature = Convert.ToBase64String(bytes);
  75. Obj.Add("OssUrl", OssUrl);
  76. Obj.Add("AccessKeyId", AccessKeyId);
  77. // Obj.Add("AccessKeySecret", AccessKeySecret);
  78. Obj.Add("Policy", policyBase64);
  79. Obj.Add("Expiration", expire);
  80. Obj.Add("Signature", Signature);
  81. Obj.Add("dir", dir);
  82. return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
  83. }
  84. #endregion
  85. #region 编辑器上传图片
  86. public object EditorUpload([FromForm] IFormCollection rf)
  87. {
  88. //文件保存目录路径
  89. String savePath = "/up/v2/";
  90. //文件保存目录URL
  91. String saveUrl = "/up/v2/";
  92. //定义允许上传的文件扩展名
  93. Hashtable extTable = new Hashtable();
  94. extTable.Add("image", "gif,jpg,jpeg,png,bmp");
  95. extTable.Add("flash", "swf,flv");
  96. extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
  97. extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
  98. //最大文件大小
  99. long maxSize = 1073741824000;
  100. IFormFile imgFile = rf.Files["imgFile"];
  101. if (imgFile == null)
  102. {
  103. showError("请选择文件。");
  104. }
  105. String dirPath = function.getPath(AppConfig.Oss.PathName + savePath);
  106. if (!Directory.Exists(dirPath))
  107. {
  108. //showError("上传目录不存在。");
  109. Directory.CreateDirectory(dirPath);
  110. }
  111. String fileName = imgFile.FileName;
  112. String dirName = "";
  113. if (String.IsNullOrEmpty(dirName))
  114. {
  115. if (fileName.ToLower().EndsWith(".mp4") || fileName.ToLower().EndsWith(".mp3"))
  116. {
  117. dirName = "media";
  118. }
  119. else
  120. {
  121. dirName = "image";
  122. }
  123. }
  124. if (!extTable.ContainsKey(dirName))
  125. {
  126. showError("目录名不正确。");
  127. }
  128. String fileExt = Path.GetExtension(fileName).ToLower();
  129. if (imgFile.Length > maxSize)
  130. {
  131. showError("上传文件大小超过限制。");
  132. }
  133. if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
  134. {
  135. showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
  136. }
  137. //创建文件夹
  138. dirPath += dirName + "/";
  139. saveUrl += dirName + "/";
  140. if (!Directory.Exists(dirPath))
  141. {
  142. Directory.CreateDirectory(dirPath);
  143. }
  144. String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
  145. dirPath += ymd + "/";
  146. saveUrl += ymd + "/";
  147. if (!Directory.Exists(dirPath))
  148. {
  149. Directory.CreateDirectory(dirPath);
  150. }
  151. String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
  152. String filePath = dirPath + newFileName;
  153. using var fs = new FileStream(filePath, FileMode.Create);
  154. imgFile.CopyTo(fs);
  155. String fileUrl = saveUrl + newFileName;
  156. if (dirName != "media")
  157. {
  158. if (!function.check_pic(filePath))
  159. {
  160. System.IO.File.Delete(filePath);
  161. return null;
  162. }
  163. if (function.getImgRule(filePath)["width"] > 2000)
  164. {
  165. String newFileName_sl = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + "_sl" + fileExt;
  166. function.imgcut(2000, filePath, dirPath + newFileName_sl);
  167. System.IO.File.Delete(filePath);
  168. fileUrl = saveUrl + newFileName_sl;
  169. }
  170. }
  171. Hashtable hash = new Hashtable();
  172. hash["error"] = 0;
  173. hash["url"] = AppConfig.Oss.SourceHost + "/" + AppConfig.Oss.PathName + fileUrl;
  174. OssHelper.Instance.ScanQueue(fileUrl, "");
  175. return JsonMapper.ToJson(hash);
  176. }
  177. private object showError(string message)
  178. {
  179. Hashtable hash = new Hashtable();
  180. hash["error"] = 1;
  181. hash["message"] = message;
  182. return JsonMapper.ToJson(hash);
  183. }
  184. public bool IsReusable
  185. {
  186. get
  187. {
  188. return false;
  189. }
  190. }
  191. #endregion
  192. #region 系统-上传文件
  193. public JsonResult UploadFile([FromForm] IFormCollection rf)
  194. {
  195. IFormFile imgFile = rf.Files["file"];
  196. string path = MySystemLib.SystemPublicFuction.GetFilePath(imgFile, AppConfig.Oss.PathName + "/uploadfile/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/");
  197. OssHelper.Instance.ScanQueue(path, "");
  198. Dictionary<string, string> obj = new Dictionary<string, string>();
  199. obj.Add("FileName", path);
  200. return Json(obj);
  201. }
  202. #endregion
  203. #region 系统-上传图片
  204. public JsonResult UploadPhoto([FromForm] IFormCollection rf)
  205. {
  206. IFormFile imgFile = rf.Files["Icon"];
  207. string Icon = MySystemLib.SystemPublicFuction.GetPicPath(imgFile, AppConfig.Oss.PathName + "/upload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/");
  208. OssHelper.Instance.ScanQueue(Icon, "");
  209. return Json(new AppResultJson() { Status = "1", Info = "", Data = Icon });
  210. }
  211. #endregion
  212. #region 系统-上传图片
  213. public JsonResult UploadPhotoByBase64(string value)
  214. {
  215. value = value.Replace("data:image/png;base64,", "");
  216. string base64str = HttpUtility.UrlDecode(value).Replace(" ", "+");
  217. string dummyData = base64str.Replace("%", "").Replace(",", "").Replace(" ", "+");
  218. if (dummyData.Length % 4 > 0)
  219. {
  220. dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
  221. }
  222. string Icon = function.base64StringToImage(dummyData, "/" + AppConfig.Oss.PathName + "/upload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/", "MT" + function.MD5_16(Guid.NewGuid().ToString()) + ".png");
  223. // OssHelper.Instance.ScanQueue(Icon, "");
  224. return Json(new AppResultJson() { Status = "1", Info = "", Data = Icon });
  225. }
  226. #endregion
  227. #region 系统-layui上传文件
  228. public JsonResult LayUIUpload([FromForm] IFormCollection rf, string Path = "", string Resize = "")
  229. {
  230. IFormFile imgFile = rf.Files[0];
  231. string Icon = MySystemLib.SystemPublicFuction.GetFilePath(imgFile, Path + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/", false);
  232. string piccut = "";
  233. if (!string.IsNullOrEmpty(Resize) && (imgFile.FileName.ToLower().EndsWith(".png") || imgFile.FileName.EndsWith(".jpg")))
  234. {
  235. JsonData data = JsonMapper.ToObject(Resize);
  236. int width = int.Parse(data["width"].ToString());
  237. int height = int.Parse(data["height"].ToString());
  238. int quality = int.Parse(data["quality"].ToString());
  239. piccut = Icon.Replace(".", "s.");
  240. function.imgcut2(width, height, function.getPath(Icon), function.getPath(piccut));
  241. System.IO.File.Delete(function.getPath(Icon));
  242. }
  243. else
  244. {
  245. piccut = Icon;
  246. }
  247. return Json(new AppResultJson() { Status = "1", Info = "", Data = piccut });
  248. }
  249. #endregion
  250. #region 图片转base64
  251. public string ImgToBase64(string path)
  252. {
  253. path = HttpUtility.UrlDecode(path);
  254. return function.imageToBase64String(function.getPath(path));
  255. }
  256. #endregion
  257. }
  258. }