Cannot Upload Image (HttpPostedFileBase is Null)

2019-02-15 19:10发布

I tried to have an images uploader but when I click the browse and select image then submit my form the HttpPostedFileBase is null. Is there missing with my implementation? Please help.

View

<form action="Home/UploadImage" method="POST">
    <p>
        <input type="file" accept="image/x-png, image/gif, image/jpeg" name="projectBgImage" id="projectBgImage"/>
    </p>
    <input type="submit" value="submit"/>
</form>

Home Controller

 public ActionResult UploadImage(HttpPostedFileBase projectBgImage)
    {
        return View();
    }

Debug Image

enter image description here

2条回答
Juvenile、少年°
2楼-- · 2019-02-15 20:02

add enctype attribute your form element

<form action="Home/UploadImage" method="POST" enctype="multipart/form-data"> 

I suggest you to use BeginForm html-helper like this:

@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { id = "form", enctype="multipart/form-data" }))
{
    <p>
        <input type="file" accept="image/x-png, image/gif, image/jpeg" name="projectBgImage" id="projectBgImage"/>
    </p>
    <input type="submit" value="submit"/>
}

and Action Method with [HttpPost] annotation

[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase projectBgImage)
{
    return View();
}

Extra Information : A nice blog post by Phil Haack Asp.net MVC Upload

查看更多
对你真心纯属浪费
3楼-- · 2019-02-15 20:03

In the View an enctype attribute is required to be set to multipart/form-data

using (Html.BeginForm("ImageUp", "YourUpController", FormMethod.Post, new { enctype = "multipart/form-data" }))

Second, On top of your action method make sure you have the HTTPPOST attribute.

[HttpPost]
public ActionResult SaveFile(HttpPostedFileBase projectBgImage)
查看更多
登录 后发表回答