1. 程式人生 > >Asp.net MVC中上傳圖片

Asp.net MVC中上傳圖片

檢視程式碼

@using (Html.BeginForm(“Add”,”Yifu”, FormMethod.Post, new { enctype = “multipart/form-data” }))
//注意enctype = “multipart/form-data” }必不可省
{


@Html.EditorFor(model => model.img, new { htmlAttributes = new { @class = “form-control”, type = “file” } })
@Html.ValidationMessageFor(model => model.img, “”, new { @class = “text-danger” })

}

控制器程式碼

HttpPostedFileBase file = Request.Files[0]; //用於獲取上傳的檔案
var fileName = file.FileName; //獲取檔案的名字(包括字尾)
var filePath = Server.MapPath(“/Images/yifu/”); //將虛擬路徑轉化為物理路徑
file.SaveAs(Path.Combine(filePath, fileName)); //儲存檔案內容