2

I have an ASP.NET MVC 3 application. I need to implement a file uploader action within it. For some reason, when I post my form, the Request.Files collection is empty. I have been able to confirm this by setting a breakpoint. So I know that I'm reaching the action. However, I can't figure out why the Request.Files collection is empty. Here are my relevant HTML, AreaRegistration, and Controller snippets.

index.html

<form action="/files/upload/uniqueID" method="post" enctype="multipart/form-data">
    <div>Please choose a file to upload.</div>
    <div><input id="fileUpload" type="file" /></div>

    <div><input type="submit" value="upload" /></div>
</form>

MyAreaRegistration.cs

context.MapRoute(
  "FileUpload",
  "files/upload",
  new { action = "UploadFile", controller = "Uploader" }
);

UploaderController.cs

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID)
{
  foreach (string file in Request.Files)
  {
    // I never get here :(
  }

  return View();
}

I have not made any changes to the default web.config file. Is there some setting I need to add? I can't figure out why the Request.Files collection would be empty. Can someone please help me?

Thank you so much!

2
  • Have you tried using the Html.Form() helper?
    – jrummell
    Commented Jan 10, 2012 at 13:21
  • possible duplicate of File upload MVC
    – jrummell
    Commented Jan 10, 2012 at 13:23

2 Answers 2

1

You should use HttpPostedFileBase for you controller and do something like that

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{

    if (file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
        file.SaveAs(path);
    }

    return RedirectToAction("Index");
}

And for the view

<form action="" method="post" enctype="multipart/form-data">

    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />

    <input type="submit" />
</form>

Check Phil Haack blog here for this problem: Uploading a File (Or Files) With ASP.NET MVC

1

I believe the problem is with your action attribute in your <form /> tag:

action="/files/upload/uniqueID"

I think upon post it is trying to pass the string "uniqueID" to your Action method. When you hit your breakpoint, what is the value of your uniqueID parameter set to when you reach the action method UploadFile()?

Use the HtmlHelper.BeginForm() method to use Razor to construct the form.

1
  • I need to POST a value for UniqueID though. In other words, I need to POST an ID value and a collection of Files to upload. How do I do that?
    – user609886
    Commented Jan 11, 2012 at 17:56

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.