0

I'm trying to simply Upload file via MVC3 this is my View :

@{
    ViewBag.Title = "Pic";
    Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
}

@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post))
{
    <input name="uploadFile" type="file" />
    <input type="submit" value="Upload File" />
}

and this is my actions :

public ActionResult FileUpload()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FileUpload(HttpPostedFileBase uploadFile)
        {
            if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                                               Path.GetFileName(uploadFile.FileName));
                uploadFile.SaveAs(filePath);
            }
            return View();
        }

what is wrong with my code ?? I have this Error

Object reference not set to an instance of an object.

in this line

 if (uploadFile.ContentLength > 0)
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
Eric Nielsen
  • 533
  • 2
  • 9
  • 25

3 Answers3

2

You should add enctype attribute to the form.

@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post,
                       new { enctype = "multipart/form-data" }))
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
0

Add new { enctype = "multipart/form-data" } as parameter to your form and you're good to go. It will look like:

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

And don't check the file size for existence control. I suggest controlling if it's null in the controller side.

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
0

replace

@using (Html.BeginForm("FileUpload", "Blog", FormMethod.Post))

with

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

to learn more about the meaning of enctype="multipart/form-data", see here

Community
  • 1
  • 1
Luke94
  • 712
  • 5
  • 14