Upload Photo To MVC 4 Applications

亡梦爱人 提交于 2019-12-02 19:48:05

The problem is that you have a property in your view model called File which is of type byte[] and you are also using an action parameter called file of type HttpPostedFileBase. The problem is that when the model binder encounters a property on your model of type byte[] it attempts to bind its value from the request value using base64. Except that inside the request you have a multipart/form-data encoded value of the uploaded file and you get an exception.

The correct way to fix this is to use view models instead of passing your domain models to the views:

public class PhotoViewModel
{
    public HttpPostedFileBase File { get; set; }

    ... other properties
}

and the controller action will now become:

[HttpPost]
public ActionResult Upload(PhotoViewModel model)
{
    if (ModelState.IsValid)
    {
        // map the domain model from the view model that the action
        // now takes as parameter
        // I would recommend you AutoMapper for that purpose
        Photo photo = ... 

        // Pass the domain model to a DAL layer for processing
        Repository.Save(photo);

        return RedirectToAction("Index");
    }
    return View(photo);
}

The poor way and totally not recommended by me is to rename your file input to trick the model binder:

<input name="PhotoFile" id="File" type="file"/>

and your controller action:

[HttpPost]
public ActionResult Upload(Photo photo, HttpPostedFileBase photoFile)
{
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!