这是一个控制器操作方法,我必须上传用户的个人资料图像...
[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“……这就是它被保存的方式。
如果这还不够奇怪,在我开始向文件上传添加逻辑之前,它确实起作用了,但这真的不应该与它有任何关系,因为它会将所有这些都向上传递……
有没有人知道这里发生了什么,为什么它会这样做,我做错了什么吗?
发布于 2012-01-30 02:35:34
UpdateModel()使用来自控制器的值提供者的值更新您的配置文件对象-例如,POST参数等。如果它找到一个名为"ProfilePhotoPath“的POST参数,您的profile.ProfilePhotoPath属性将被设置为该值,覆盖您刚刚手动设置的值。
您的名称字段(或用于将文件发送到服务器的任何方法)似乎有一个<input type="file">属性:"ProfilePhotoPath“。该字段将在服务器上转换为一个HttpPostedFileWrapper对象,其中包含有关发布的文件的信息(内容长度、类型、文件名等)。它是UpdateModel将分配给您的profile.ProfilePhotoPath属性的对象(因为它与属性具有相同的名称)。由于它将一个对象分配给一个字符串属性,因此它将强制该对象成为一个字符串,从而产生"System.Web.HttpPostedFileWrapper“。
https://stackoverflow.com/questions/9055466
复制相似问题