1

I want to allow my user to upload different documents using different upload button.

My question: Is there any way that I can get the type of document being uploaded?

Consider a scenario: My user may upload their Resume by clicking on resume upload button & user may upload cover letter by clicking on Upload cover letter button.

How would I know whether the uploaded content is resume or cover letter.

All I get in the controller is HttpPostedFileBase[].

[HttpPost]
public ActionResult Create(FormCollection collection, HttpPostedFileBase[] upload)
{
    try
    {
        // TODO: Add insert logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

One question I found similar to my question is: Get file names from multiple files uploaded. The approach they are following, is it efficient? I mean I will have 8-10 Upload buttons on my page. Having 8-10 parameters in Post method looks odd.

Community
  • 1
  • 1
Gyandeep
  • 119
  • 1
  • 11

3 Answers3

1

Basically, you have three options, unless you wanted to create a ViewModel-type class which wraps all your files.

  1. You can use only one file upload button, with multiple="multiple", and accept a HttpPostedFileBase[] in your action (which prevents you from distinguishing the files from one another).

  2. You can use multiple file upload buttons with different names, and accept multiple parameters in your controller (which you said you don't want to do).

  3. You can use multiple file upload buttons, index the names appropriately, and add comments so you know which file is which.

Example:

HTML:

<input type="file" name="files[0]" /> <!-- resume -->
<input type="file" name="files[1]" /> <!-- cover letter -->
<input type="file" name="files[2]" /> <!-- whatever else -->

In your HttpPost:

[HttpPost]
public ActionResult Create(HttpPostedFileBase[] files)
{
    // files[0] == resume
    // files[1] == cover letter
    // files[2] == whatever
}

I don't know why you wouldn't just name the file uploads resume and coverLetter, and then accept those parameters in your post. Personally, I think accepting multiple parameters is the best way to approach this kind of thing - but if you don't want to do that for some reason, this isn't a bad solution either.

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
0

You can know the file type using the property HttpPostedFileBase.ContentType

Yazan Ati
  • 62
  • 2
0

You can break up each file upload into a separate form on the screen. Then target separate actions on the controller. Really, with so many uploads, isn't it better just to break them out into separate controllers? You can target many controllers per screen.

beautifulcoder
  • 10,832
  • 3
  • 19
  • 29