0

This is a follow-up question to ASP.NET MVC 3 - File Upload. I have a URL syntax that I cannot change. I need to upload files to a URL in the syntax of "/person/{personID}/files". Currently, I am trying the following:

index.html

<form action="/person/2/files" 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>

The personID parameter value is dynamically populated when the form loads. Regardless, when I click "upload", I'm posting back to the following action:

UploadController.cs

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID)
{
  foreach (string file in Request.Files)
  {
    // Request.Files is empty
  }

  return View();
}

How do I POST both a collection of files AND a parameter using the URL syntax of "/person/{personID}/files"? I know this is a very specific request. I have run out of time on my project and I'm totally confused why the approach I'm using doesn't work. Can somebody please help me?

Thank you so very much.

1 Answer 1

6

Assuming you have a route defined for this custom url:

routes.MapRoute(
    "Upload",
    "person/{uniqueid}/files",
    new { controller = "Upload", action = "UploadFile" }
);

you just need to give your file input a name:

<div><input id="fileUpload" type="file" name="file" /></div>

Also I would recommend you to use action arguments instead of looping through Request.Files:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID, HttpPostedFileBase file)
{
    return View();
}

and if you wanted to post multiple files:

<div><input type="file" name="files" /></div>
<div><input type="file" name="files" /></div>
<div><input type="file" name="files" /></div>
...

use a collection:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID, IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

You might also find the following blog post useful.

Or even better, use a view model:

public class MyViewModel
{
    public int UniqueID { get; set; }
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}

and then:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(MyViewModel model)
{
    return View();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thank you so much. The "name" attribute solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.