Request.Files.Count always 0 while uploading image in MVC 5
Asked Answered
C

5

25

I have a Post controller on a model with some string fields and an image. Exact identical code works on MVC4 but in MVC 5 the Request.Files.Count is always 0

My model has byte[] for image rather than HttpPostedFileBase

My View:

@using (Html.BeginForm("Create", "HotelManager", FormMethod.Post, new { enctype = "multipart/form-data", data_ajax = "false" }))
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(model => model.Title, new { @class = "form-control" })
    @Html.TextAreaFor(model => model.Description, new { @class = "form-control", @rows = "7" })
    <input type="file" class="form-control filestyle">
    <input type="submit" value="Submit" class="btn btn-block" />
}

I have tried omitting data_ajax = "false" but no use.

My Post Controller is as follows:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Title,Description,Image")] Hotel hotel)
    {
        if (ModelState.IsValid)
        {
            // deal with the uploaded file
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    // Code to process image, resize, etc goes here
                }
            }

        // Other code to add the hotel to db goes here
    }

In the debugger I see that the Request.Files.Count is always zero, I don't know why? I have copied over both the view and controller code from another MVC4 project where it works fine.

Key Value
Request POST /HotelManager/Create HTTP/1.1
Accept  text/html, application/xhtml+xml, */*
Referer http://localhost:4976/HotelManager/Create
Accept-Language en-US,en;q=0.5
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; ASU2JS; rv:11.0) like Gecko
Content-Type    multipart/form-data; boundary=---------------------------7de207070a24
Accept-Encoding gzip, deflate
Host    localhost:4976
Content-Length  946
DNT 1

And in the IE Developer window I see that the form body is empty.

Cece answered 16/3, 2014 at 10:59 Comment(0)
C
49

I wasted so much time and it turns out that all I needed to do was to use the name attribute as well

 <input type="file" name="somename"> 

the name attribute was missing in my new project.

Cece answered 16/3, 2014 at 19:32 Comment(2)
Ugh! Spent atleast 30 minutes wasted on this. Good catch!Beshore
The other possibility this happens is if you miss enctype="multipart/form-data" on the form tag.Sloat
E
44

You need to change the post method

Need to add:

new { enctype = "multipart/form-data" }

Here is complete form tag

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

See how can you post multiple files

Excise answered 24/4, 2014 at 17:37 Comment(3)
This may not have been the OP's issue, but it resolved my issue... didn't know that enctype was necessary.Parabola
Same here. I forgot to add enctype since I rarely use itAlodee
==> enctype="multipart/form-data" on the form tagSloat
E
12

To add on You need to change the post method.

Need to add:

new { enctype = "multipart/form-data" }

Here is complete form tag

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

Those lines are essential; without them, you will not be able to save an input of type file. I sat for 6 hours trying to figure that out.

Eat answered 19/7, 2015 at 0:4 Comment(0)
D
2

One of the reasons why Request.Files.Count becomes 0 is when you try to upload a file larger than the maxRequestLength specified on Web.config file. Make sure to check this value if you are having an issue with Request.Files.Count.

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="4096" />
  </system.web>
</configuration>

UPDATE: This answer might not be directly related to OP's issue, but since google lists this post top for Request.Files.Count=0 issue, posted the answer which worked for me.

Davy answered 26/2, 2018 at 11:4 Comment(1)
This answer might not be directly related to OP's issue, but since google lists this post top for Request.Files.Count=0 issue, posted the answer which worked for me.Davy
E
0

While uploading the Image I found one scenario. If you are storing image in DBContext and calling any API with async-await, then save Image in database before you call any API. Otherwise Content-length becomes 0. I have debugged this clearly then realized. We need to perform save operation for database before async call. However, name attribute is must for file input type and Post method and enctype multipart/form-data is must required in HTML beginform.

Also you can try getting file base by,

HttpPostedFileBase fileBase = Request.Files["file_name"];
Empiric answered 16/9, 2020 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.