這裏是一個控制器操作方法,我要上傳用戶的個人資料圖片...MVC 3的UpdateModel和調用SaveChanges
[HttpPost]
public ActionResult UploadPhoto(int id, FormCollection form)
{
Profile profile = db.Profiles.Find(id);
var file = Request.Files[0];
if (file.ContentLength > 512000)
{
ModelState.AddModelError(string.Empty, "Please limit your photo to 500 KB");
}
bool IsJpeg = file.ContentType == "image/jpeg";
bool IsPng = file.ContentType == "image/png";
bool IsGif = file.ContentType == "image/gif";
if (!IsJpeg && !IsPng && !IsGif)
{
ModelState.AddModelError(string.Empty, "Only .jpeg, .gif, and .png images allowed");
}
if (file == null || file.ContentLength <= 0)
{
ModelState.AddModelError(string.Empty, "You must select an image to upload");
}
if (ModelState.IsValid)
{
try
{
string newFile = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/Content/users/" + User.Identity.Name + "/" + newFile));
profile.ProfilePhotoPath = "/Content/users/" + User.Identity.Name + "/" + newFile;
UpdateModel(profile);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
當我嘗試上傳的圖像,並通過它一步......
當應用程序碰到這條線:
profile.ProfilePhotoPath = "/Content/users/" + User.Identity.Name + "/" + newFile;
它顯示了ProfilePhotoPath值爲 「System.Web.HttpPostedFileWrapper」
現在,當應用程序打下一行:
UpdateModel(profile);
它顯示了ProfilePhotoPath值爲「/Content/users/WebWired/myprofilepic.png」,因爲它應該...
但隨後,當應用程序打下一行:
db.SaveChanges();
突然之間ProfilePhotoPath值是「System.Web.HttpPostedFileWrapper」了......這是它是如何保存的?
如果不是奇怪的是,它的工作之前,我開始添加邏輯文件上傳,但真的不應該有什麼關係,因爲它經過了這一切起來......
不任何人都明白這裏發生了什麼,爲什麼這樣做,我做錯了什麼?
「看來‘ProfilePhotoPath’是你上傳文件的格式名稱。」你是對的,這是...哇,謝謝你,一個完整的DUH!我的時刻......再次完美地工作。 – 2012-01-29 18:57:34
我剛編輯擺脫了很多關於張口閉口我是如何得到這個結論的(完全忘記了控制器::的UpdateModel是MVC提供的方法 - 我從來沒有使用它)。那是*我* DUH!時刻。 :-) – JimmiTh 2012-01-29 19:04:25