4

I added an input file field but it's always null on the controller. What am I missing?

Here's the code for both my view and controller.

view:

...
@using (Html.BeginForm())
{
    ...

    <input type=file name="file" id="file" class="post-attachment" />

    ...
}

controller:

[HttpPost]
public ViewResult _Details(HttpPostedFileBase file, ViewTopic viewTopic, string SearchField, string submitBtn)
{
    // save file to server
    if (file != null && file.ContentLength > 0)
    {
        var fileName = DateTime.Today.ToString("yy.MM.dd") + Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/Attachments"), fileName);
        file.SaveAs(path);
    }

...
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Bahamut
  • 1,929
  • 8
  • 29
  • 51

2 Answers2

5

You need to explicitly set the enctype of the form:

@using(Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    ...
}
Adam Flanagan
  • 3,052
  • 23
  • 31
  • Worked. Thanks! Although there seems to be a limit about the files since it keeps having an error which might be a file size or file type but I'll save that for another question. – Bahamut Sep 05 '11 at 16:11
1

You need to change your form to something like -

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload"/>
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

There's a load more info (including the sample above) in this question - Html helper for <input type="file" />

Community
  • 1
  • 1
ipr101
  • 24,096
  • 8
  • 59
  • 61