先建立前端传值到后端需要承接的资料类别
public class ImageDataModel{ /// <summary>图片名称</summary> public string Name { get; set; } /// <summary>大小</summary> public long Size { get; set; } /// <summary>副档名</summary> public string Type { get; set; } /// <summary>宽</summary> public int Width { get; set; } /// <summary>高</summary> public int Height { get; set; } /// <summary>base64图档资料</summary> public string Data { get; set; } public bool CheckData(int LimitWidth, int LimitHeight) { if (!Regex.IsMatch(Type.ToString(), "^image/(png|jpeg|jpg)$")) { Message = "图片格式错误"; return false; } if (Width < LimitWidth || Height < LimitHeight || Width % LimitWidth != 0 || Height % LimitHeight != 0 || Width / LimitWidth != Height / LimitHeight) { Message = $"图片尺寸比例必须为{LimitWidth}px*{LimitHeight}px"; return false; } if (Size > Width * Height * 8) { Message = "图片大小错误"; return false; } if (Size > 1048576) //1024*1024 = 1MB { Message = "图片不得大于1MB"; return false; } return true; }}
再来在后端建立图片上传的方法类别
public class UplaodFile{ /// <summary>图片上传</summary> /// <param name="Path">路径</param> /// <param name="FileData">base64的字串</param> /// <returns>上传是否成功</returns> public bool UploadImg(string Path, string FileData) { try { byte[] byteimg = Convert.FromBase64String(FileData); using (FileStream MyFile = new FileStream(Path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { MyFile.Write(byteimg, 0, byteimg.Length); MyFile.Flush(); } } catch (Exception e) { return false; } return true; }}
后端使用方式
public ActionResult UploadImage(ImageDataModel Image){ UplaodFile file = new UplaodFile(); string backPath = System.Web.Hosting.HostingEnvironment.MapPath("/Upload"); backPath += "\\Image"; Directory.CreateDirectory(backPath); if (Image != null) { string fullName = $"{Guid.NewGuid().ToString()}.{Image.Type.Split('/')[1]}"; file.UploadImg($"{backPath}\\{fullName}", Image.Data.Split(',')[1]); } return Json(new { Status = "SUCCESSFUL" });}