public ResponsResult Post([FromBody] FileUploadModel model) { ResponsResult result = new ResponsResult(); try { var ext = System.IO.Path.GetExtension(model.FileName); if (string.IsNullOrEmpty(ext)) { ext = ".jpg"; } string _fileName = $"{model.Type}_{DateTime.Now.ToString("yyyyMMddHHmmssfffffff")}{ext}"; var _virtual = PathServerUtility.Combine(System.Enum.GetName(typeof(FileType), model.Type), model.Id.ToString(), _fileName); var webApiPath = ConfigLocator.Instance[TbConstant.WebSiteKey] + "/api/UploadBase64File"; var sign = Security.Sign(Domain.Config.TbConstant.UploadKey, _virtual); model.Picture = Convert.ToBase64String(ImageHandler.ShrinkImage(ImageHandler.Base64ToBytes(model.Picture))); string response; if (!string.IsNullOrEmpty(model.WaterMarks)) { response = HttpUtility.PostString(webApiPath, new { sign = sign, base64 = model.Picture, fileName = _virtual, watermarks = model.WaterMarks }.GetJson(), "application/json"); } else { response = HttpUtility.PostString(webApiPath, new { sign = sign, base64 = model.Picture, fileName = _virtual }.GetJson(), "application/json"); } var uploadModel = (response.GetModel <ResponsResult>().Data as Newtonsoft.Json.Linq.JObject).ToObject <UploadModel>(); result.Data = uploadModel; return(result); } catch (Exception ex) { Log4Net.Error($"[上传图片异常]_:{ex}"); return(result.SetError("上传图片异常")); } }
public ResponsResult UploadBase64File([FromBody] ReqModel model) { ResponsResult result = new ResponsResult(); if (string.IsNullOrWhiteSpace(model.Base64) || string.IsNullOrEmpty(model.FileName)) { var di = PathServerUtility.MapPath(TbConstant.DefaultHeadPicture); FileInfo fi = new FileInfo(di); UploadModel uploadModel = new UploadModel { FileName = fi.Name, FullName = fi.FullName, Extension = fi.Extension, Length = fi.Length, VirtualPath = model.FileName ?? TbConstant.DefaultHeadPicture, FullVirtualPath = PathServerUtility.CombineWithRoot(model.FileName ?? TbConstant.DefaultHeadPicture), }; result.Data = uploadModel; } else { if (!Security.ValidSign(model.Sign, model.FileName, TbConstant.UploadKey)) { return(result.SetStatus(ErrorCode.InvalidSign)); } var filePath = PathServerUtility.MapPath(model.FileName); FileInfo fi = new FileInfo(filePath); var bytes = ImageHandler.Base64ToBytes(model.Base64); if (!fi.Directory.Exists) { fi.Directory.Create(); if (!string.IsNullOrEmpty(model.Watermarks)) { MemoryStream ms = new MemoryStream(bytes); using (Image image = Image.FromStream(ms)) { using (Bitmap bitmap = new Bitmap(image.Width, image.Height)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.Clear(Color.Transparent); graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel); StringFormat strFormat = new StringFormat(); strFormat.Alignment = StringAlignment.Center; graphics.DrawString(model.Watermarks, new Font("华文彩云", 16, FontStyle.Italic | FontStyle.Bold) , Brushes.Sienna, new PointF(image.Width / 2, image.Height - image.Height / 8), strFormat); bitmap.Save(filePath, ImageFormat.Png); } } } } } else { using (var fs = fi.Create()) { fs.Write(bytes, 0, bytes.Length); fs.Flush(true); fi.Refresh(); } } var webSite = ConfigLocator.Instance[TbConstant.WebSiteKey]; UploadModel uploadModel = new UploadModel { FileName = fi.Name, FullName = fi.FullName, Extension = fi.Extension, Length = fi.Length, VirtualPath = model.FileName, FullVirtualPath = PathServerUtility.CombineWithRoot(webSite, model.FileName), }; result.Data = uploadModel; } return(result); }
List <upload> uploadRemote(string path) { List <upload> list = new List <upload>(); string savePath = PathServerUtility.MapPath(path); //保存文件地址 //目录验证 if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } string uri = System.Net.WebUtility.UrlDecode(this.Params("upfile")); string[] imgUrls = null; if (string.IsNullOrEmpty(uri)) { uri = System.Net.WebUtility.UrlDecode(this.Params("upfile[]")); imgUrls = Regex.Split(uri, ",", RegexOptions.IgnoreCase); } else { uri = uri.Replace("&", "&"); imgUrls = Regex.Split(uri, "ue_separate_ue", RegexOptions.IgnoreCase); } for (int i = 0, len = imgUrls.Length; i < len; i++) { try { var imgUrl = imgUrls[i]; var upload = new upload { source = imgUrl, state = "SUCCESS" }; if (!imgUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !imgUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { continue; } //格式验证 int temp = imgUrl.LastIndexOf('.'); var ext = imgUrl.Substring(temp).ToLower(); if (Array.IndexOf(filetype, ext) == -1) { upload.state = "ERROR"; continue; } var stream = HttpUtility.DownBytes(imgUrl); if (stream == null || stream.Length == 0) { continue; } var tmpName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffffff")}_{i}{ext}"; //写入文件 using (FileStream fs = new FileStream(Path.Combine(savePath, tmpName), FileMode.CreateNew)) { //stream.CopyTo(fs); fs.Write(stream, 0, stream.Length); fs.Flush(); } upload.url = PathServerUtility.CombineWithRoot(path, tmpName); list.Add(upload); } catch { } } return(list); }
object uploadLocal(string path) { //文件上传状态,初始默认成功,可选参数{"SUCCESS","ERROR","SIZE","TYPE"} string state = "SUCCESS"; string title = string.Empty; string oriName = string.Empty; string filename = string.Empty; string url = string.Empty; string currentType = string.Empty; //保存路径 string uploadpath = PathServerUtility.MapPath(path); try { IFormFile uploadFile = Request.Form.Files[0]; title = uploadFile.FileName.ToLower(); //目录验证 if (!Directory.Exists(uploadpath)) { Directory.CreateDirectory(uploadpath); } //格式验证 string[] temp = uploadFile.FileName.Split('.'); currentType = "." + temp[temp.Length - 1].ToLower(); if (Array.IndexOf(filetype, currentType) == -1) { state = "文件类型不正确"; } else //大小验证 if (uploadFile.Length / 1024 > size) { state = $"文件不能超过{size / 1024}M"; } //获取图片描述 if (Request.Query["pictitle"].Count > 0) { if (!String.IsNullOrEmpty(Request.Query["pictitle"])) { title = Request.Query["pictitle"]; } } //获取原始文件名 if (Request.Query["fileName"].Count > 0) { if (!String.IsNullOrEmpty(Request.Query["fileName"])) { oriName = Request.Query["fileName"].ToString().Split(',')[1]; } } //保存图片 if (state == "SUCCESS") { if (System.IO.File.Exists(Path.Combine(uploadpath, title))) { state = "ERROR"; } else { filename = DateTime.Now.ToString("yyyyMMddHHmmssffffff") + currentType; FileInfo fi = new FileInfo(Path.Combine(uploadpath, filename)); using (var fs = fi.OpenWrite()) { uploadFile.CopyTo(fs); fs.Flush(); } } url = PathServerUtility.CombineWithRoot(path, filename); } } catch (Exception) { state = "ERROR"; } return(new { url, title, original = oriName, state }); }