1

I'm having a problem with uploading multiple files to C# and loop through them. I found a question with a similar problem but nobody answered it.

I upload multiple files through an html input. The file count passes through to my controller with the correct amount relative to the amount of files I selected. However when I try to loop through each of my files it loops through the first file relative to the file count. For example if I upload 3 files it loops through the first file 3 times or if I upload 5 files it loops through the first file 5 times. It should not do this. I want it to loop through each file individually. Please help!!! here is my code:

Razor View(I'm using a bootstrap library for fileinputs called bootstrap-filestyle):

@using (Html.BeginForm("Initial", "DataCapture", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">

   <h4>Select files</h4>
   <input type="file" multiple="multiple" id="fileToUpload" name="file">

</div>

<div>
    <input type="submit" value="Capture" class="btn btn-default" />
</div>
}

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Initial(ClaimModel claimModel)
{
    if (ModelState.IsValid)
    {

        //OtherCode
        handleFile(Request.Files, c.ClaimID);

        return RedirectToAction("Index", "ClaimFiles", new { id = c.ClaimID });
    }

 //OtherCode
}


private void handleFile(HttpFileCollectionBase Files, int ClaimID)
{

    foreach (string fileName in Files)
    {
        HttpPostedFileBase file = Request.Files[fileName];
        //OtherCode
    }
//OtherCode
}

I put break points on handleFile(Request.Files, c.ClaimID); and inside foreach (string fileName in Files){...}. As I said it correctly passes through the file count if I upload 3, 4, 5 or any amount of files however it only loops through the first file that amount of times and returns the first file multiple times as well. I need it to loop through and return each file individually. How do I do this correctly?

1
  • 1
    Because you have one file input with name="file" so if you select multiple files, they all have name="file" and HttpPostedFileBase file = Request.Files["file"]; returns only the first one with that name. Use a for loop Commented Aug 5, 2016 at 12:05

2 Answers 2

4

Use Request from server, here is one example:

for (int i = 0; i < Request.Files.Count; i++)
{
  var fileDoc = Request.Files[i];  
}
Sign up to request clarification or add additional context in comments.

Comments

0

Or you can try something like this:

HttpPostedFileBase hpf = null;

foreach (string file in Request.Files)
{
    hpf = Request.Files[file] as HttpPostedFileBase;
}

Comments

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.