iT邦幫忙

0

[C#] 網站圖片上傳

c#
  • 分享至 

  • xImage
  •  

先建立前端傳值到後端需要承接的資料類別

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" });
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言