ASP.NET MVC 3 - File Upload

2019-05-23 15:57发布

问题:

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!

回答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



回答2:

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.