ImagesService.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Microsoft.Extensions.Logging;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. using Winsoft.GOV.XF.WebApi.WXCore.Data;
  10. using Winsoft.GOV.XF.WebApi.WXCore.Models;
  11. namespace Winsoft.GOV.XF.WebApi.WXCore.Services
  12. {
  13. public class ImagesService : BaseService
  14. {
  15. string[] AllowedFileExtensions = new string[] { "jpg", "gif", "png", "jpeg" };
  16. public ImagesService(XFDbContext context, ILoggerFactory loggerFactory):base(context, loggerFactory)
  17. {
  18. }
  19. public bool SaveToDisk(Asset a)
  20. {
  21. Match m = Regex.Match(a.Data, @"data:image/(\S+);base64,");
  22. if (!m.Success)
  23. return false;
  24. string exName = m.Groups[1].Value;
  25. if (!AllowedFileExtensions.Contains(exName))
  26. return false;
  27. string base64Str = Regex.Replace(a.Data, @"data:image/(\S+);base64,", "");
  28. byte[] bt = Convert.FromBase64String(base64Str);
  29. string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff.") + exName;
  30. string diskPath = "";
  31. string absPath = "";
  32. GetUploadPath(out diskPath, out absPath);
  33. File.WriteAllBytes(diskPath + "/" + filename, bt);
  34. a.Data = JsonConvert.SerializeObject(new { src = absPath + "/" + filename });
  35. return true;
  36. }
  37. void GetUploadPath(out string diskPath, out string absPath)
  38. {
  39. string upload_path = Directory.GetCurrentDirectory() + "/wwwroot";
  40. DateTime now = DateTime.Now;
  41. if (Directory.Exists(upload_path + "/images/" + now.Year) == false)//如果不存在就创建file文件夹
  42. {
  43. Directory.CreateDirectory(upload_path + "/images/" + now.Year);
  44. }
  45. if (Directory.Exists(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd")) == false)//如果不存在就创建file文件夹
  46. {
  47. Directory.CreateDirectory(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd"));
  48. }
  49. diskPath = upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd");
  50. absPath = "/images/" + now.Year + "/" + now.ToString("MMdd");
  51. }
  52. }
  53. }