前言
- 本文介紹簡單的單文件上傳,並解決了HttpPostedFileBase爲空的問題。
- 系統設計中使用了MVC的Anotation驗證。
- view界面是採用
Html.BeginForm
的形式
介紹步驟詳解
- View設置
@using (Html.BeginForm("Upload","Admin",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
///標題字段的輸入和驗證
@Html.LabelFor(model => model.Title)
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
///上傳圖片字段的驗證
@Html.LabelFor(model => model.ImgUrl)
@Html.TextBoxFor(model => model.ImgUrl,
new { @type="file"})
@Html.ValidationMessageFor(model => model.ImgUrl)
//上傳按鈕
<input type="submit" value="確認添加" />
}
- Controller Action設置
[HttpPost]
public ActionResult Upload(Picture pic)
{
///【注1】這樣寫是爲了避免HttpPostedFileBase爲空的問題
HttpPostedFileBase image = Request.Files["ImgUrl"];
if (image != null && image.ContentLength > 0)
{
///【注2】這裏的文件路徑名一定要合格,符合文件名規範。
///否則image.SaveAs(filePath);這句代碼會報錯。
string fileName = DateTime.Now.ToString("yyyyMMddmmssfff") + "-" + Path.GetFileName(image.FileName);
string filePath = Path.Combine(Server.MapPath("~/Upload"), fileName);
image.SaveAs(filePath);
pic.ImgUrl = "~/Upload/" + fileName;
///此處將pic信息保存到數據庫
return this.View();
}
}
注意點
View界面要設置:
FormMethod.Post, new { enctype = "multipart/form-data" }不要將
HttpPostedFileBase image
以參數的形式傳遞進來,會造成image
爲空,拿不到數據。建議採用Request.Files
的方式獲取圖片,HttpPostedFileBase image = Request.Files["ImgUrl"];
即ImgUrl爲View頁面的Name屬性值Chrome界面上傳的文件 不帶路徑名,而IE會帶路徑名,如果你不採用上述方法獲取路徑名,而是通過pic.ImgUrl的方式,採用以下代碼兼容
private String getImgUrl(String url)
{
String imgUrl = url;
if (url.LastIndexOf("\\") > -1)
{
imgUrl = url.Substring(url.LastIndexOf("\\") + 1);
}
return imgUrl;
}
文件保存在服務器上的名字要求不同不然不同用戶上傳的文件會覆蓋。造成數據的丟失錯亂。 如果保存的文件名格式錯誤,還會在下面
image.SaveAs(filePath);這裏報錯,有不少人遇到這個問題。顯示效果(上面沒有給出CSS代碼)
小結
本文介紹了MVC下文件上傳的小Demo,解決了HttpPostedFileBase爲空的問題,順便提了一些其他經常遇到的問題,文件名不重複,瀏覽器不同,拿到的路徑名不同以及 image.SaveAs(filePath)報錯問題。