using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Winsoft.GOV.XF.WebApi.WXCore.Data; using Winsoft.GOV.XF.WebApi.WXCore.Models; namespace Winsoft.GOV.XF.WebApi.WXCore.Services { public class ImagesService : BaseService { string[] AllowedFileExtensions = new string[] { "jpg", "gif", "png", "jpeg" }; public ImagesService(XFDbContext context, ILoggerFactory loggerFactory):base(context, loggerFactory) { } public bool SaveToDisk(Asset a) { Match m = Regex.Match(a.Data, @"data:image/(\S+);base64,"); if (!m.Success) return false; string exName = m.Groups[1].Value; if (!AllowedFileExtensions.Contains(exName)) return false; string base64Str = Regex.Replace(a.Data, @"data:image/(\S+);base64,", ""); byte[] bt = Convert.FromBase64String(base64Str); string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff.") + exName; string diskPath = ""; string absPath = ""; GetUploadPath(out diskPath, out absPath); File.WriteAllBytes(diskPath + "/" + filename, bt); a.Data = JsonConvert.SerializeObject(new { src = absPath + "/" + filename }); return true; } void GetUploadPath(out string diskPath, out string absPath) { string upload_path = Directory.GetCurrentDirectory() + "/wwwroot"; DateTime now = DateTime.Now; if (Directory.Exists(upload_path + "/images/" + now.Year) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(upload_path + "/images/" + now.Year); } if (Directory.Exists(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd")) == false)//如果不存在就创建file文件夹 { Directory.CreateDirectory(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd")); } diskPath = upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd"); absPath = "/images/" + now.Year + "/" + now.ToString("MMdd"); } } }