2011-02-03 27 views
8

目標:
對圖片的格式,寬度和高度進行評估,然後將其保存在我的程序中。MVC中的圖片驗證

問題:
不知道如何使用HttpPostedFileBase file,然後發送它Image newImage = Image.FromFile(xxxx);不保存圖片在我的計劃。

  1. 驗證
  2. 保存圖片在我的 「App_Data文件」
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Add(HttpPostedFileBase file) 
{ 
    if (file.ContentLength > 0) 
    { 
     Image newImage = Image.FromFile(xxxx);  
    } 

    return Index(); 
} 

回答

12

你可以這樣做在某種程度上像下面的代碼片段。請注意0​​命名空間參考,您需要爲Image.FromStream()方法。

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Add(HttpPostedFileBase httpPostedFileBase) 
{ 
    using (System.Drawing.Image image = System.Drawing.Image.FromStream(httpPostedFileBase.InputStream, true, true)) 
    { 
     if (image.Width == 100 && image.Height == 100) 
     { 
      var file = @"D:\test.jpg"; 
      image.Save(file); 
     } 
    } 

    return View(); 
}