先建立前端傳值到後端需要承接的資料類別
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" });
}