ASP.NET MVC 圖片上傳與判斷

圖片上傳, 圖片大小 尺寸檢查等

參考來源:demoshop

View:

<% using (Html.BeginForm("Create", "BackBanner", FormMethod.Post, new { @id = "CreateForm", @enctype="multipart/form-data" })) { %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationSummary(true) %>
 
<fieldset>
    <h3>BannerViewModel</h3>
    <p id ="ErrorMsg"></p>
    <table class="table">
        <tr>
            <td>上傳圖片:</td>
            <td>
                <label for="UploadPhoto">Filename:</label>
                <input type="file" name="upfile" id="upfile" />
            </td>
        </tr>
    </table>
     
    <button type="button" class="btn btn-default btn-sm" onclick="CheckData(); return false;">新增</button>
</fieldset>
<% } %>

前端的input name必須對應Action所接的參數名稱
注意,上傳檔案時Form表單需要加入屬性enctype="multipart/form-data"

[HttpPost]
public ActionResult Create(FormCollection collection, HttpPostedFileBase upfile)
{
    try
    {
        if(CheckImage(collection, upfile))
        {
            string photoName = upfile.FileName;
            // 寫入資料庫的結果
            bool SetDataResult = new BackBannerRepo().setBannerData(collection, ref photoName);
 
            // 資料成功寫入資料庫後才儲存檔案
            if (SetDataResult)
            {
                // 設定儲存路徑(含檔名)
                string savedName = Path.Combine(Server.MapPath("~/Content/images/fake/"), photoName);
                // 儲存檔案
                upfile.SaveAs(savedName);
                TempData["Message"] = "上傳成功";
                // 重新取得清單
                BannerSelection = new BackBannerRepo().getBannerSelectionList();
            }
            else
                TempData["Message"] = "輸入的資料有誤,無法寫入資料庫";
        }
 
        return RedirectToAction("Index", "BackBanner");
    }
    catch(Exception ex)
    {
        return View();
    }
}
/// <summary>
/// 確認要上傳的檔案內容
/// </summary>
/// <param name="collection"></param>
/// <param name="upfile"></param>
/// <returns></returns>
public bool CheckImage(FormCollection collection, HttpPostedFileBase upfile)
{
    using (StarBackendEntities db = new StarBackendEntities())
    {
        #region 判斷是否有選擇上傳檔案
        if (upfile == null)
        {
            TempData["Message"] = "並未選擇上傳檔案";
            return false;
        }
        #endregion
        #region  判斷檔案大小
        if (upfile.ContentLength <= 0)
        {
            TempData["Message"] = "檔案大小不可為0";
            return false;
        }
        #endregion
        #region 判斷檔案名稱
        // 取得副檔名
        string fileType = upfile.FileName.Split('.').Last().ToUpper();
        if (!(fileType.Equals("JPG") || fileType.Equals("JPEG") || fileType.Equals("PNG")))
        {
            TempData["Message"] = "只接受圖片檔";
            return false;
        }
        #endregion
        #region 判斷檔案長寬
        // 取得上傳檔案
        Image img = Image.FromStream(upfile.InputStream);
        int imgMinWidth, imgMaxWidth, imgMinHeight, imgMaxHeight;
        var tdData = db.TYPE_DATA.Find(collection["Type"].ToString());
        if (tdData != null)
        {
            imgMinWidth = tdData.MinWidth;
            imgMaxWidth = tdData.MaxWidth;
            imgMinHeight = tdData.MinHeight;
            imgMaxHeight = tdData.MaxHeight;
 
            // 判斷圖片大小是否符合
            if (!(imgMinHeight <= img.Height && img.Height <= imgMaxHeight && imgMinWidth <= img.Width && img.Width <= imgMaxWidth))
            {
                TempData["Message"] = string.Format("圖片尺寸需介於{0}~{1} x {2}~{3}", imgMinWidth, imgMaxWidth, imgMinHeight, imgMaxHeight);
                return false;
            }
        }
        else
        {
            TempData["Message"] = "資料庫查無此類型圖片";
            return false;
        }
        #endregion
    }
 
    // 執行到此表示檔案可上傳
    return true;
}