0

I have created a dynamic form generator for my company. It allows the users to create different form fields with different names. Processing the form is easy, but the file upload has been a nightmare, because the name of the form field is not known for the controller. In my case, the form field can be like this:

<input type="file" name="certificate" accept=".pdf" />

or

<input type="file" name="course-certificate" accept=".pdf, .docx" />

it can even have one or more file fields in one form

The problem is that when it goes to the post method after submitting the form, I am supposed to have a parameter for the files. It can either be a single file like:

[HttpPost]
public ActionResult Create(HttpPostedFileBase file) // For a single file upload
{
}

or

[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files) // For multiple file uploads
{
}

But I need to send the files with random names that can even have a dash in the middle. What is the solution for this? I don't want to use any kind of jQuery to prepare the form before sending it, I want to be able to send the form as it was reated and receive it in my controler just like that.

2
  • 2
    You would need to loop through Request.Files Commented Jul 30, 2018 at 22:57
  • Gonna try that and I'll tell you, so I can accept your answer as the correct one. Commented Jul 30, 2018 at 23:00

1 Answer 1

1

There is HttpRequest.Files collection available which represents uploaded files from <input type="file" /> elements by using form submit. You just need to iterate it using either for or foreach loop inside controller action marked with HttpPostAttribute:

for-loop version

for (int i = 0; i < Request.Files.Count; i++)
{
    var uploadedFile = Request.Files[i] as HttpPostedFileBase;

    if (uploadedFile.ContentLength > 0)
    {
        // do something
    }
}

foreach-loop version

foreach (string fileName in Request.Files)
{
    var uploadedFile = Request.Files[fileName] as HttpPostedFileBase;

    if (uploadedFile.ContentLength > 0)
    {
        // do something
    }
}

Note: With foreach loop, if Request.Files collection has duplicate file names, the first matched file name will be stored multiple times, even they have different sizes (related issue here). Hence, for loop approach is more preferred (and you can still get corresponding file name with uploadedFile.FileName).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I used your solution. Important to notice that the field names (as in the form) are stored in a collection: Request.Files.AllKeys

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.