C# getting all files in request.file

2019-09-06 21:23发布

问题:

I am trying to upload a group of files, however when i loop through the files only the first file is ever saved, despite being looped through the correct number of times. So i can only upload the first file, not multiple files if they have been selected.

I have this code I have seen in a couple of examples.

        foreach (string fileName in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[fileName];
            //Save file content goes here
            fName = file.FileName;

Here is the Html,

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

        <textarea rows="10" cols="50" class="ListOfFiles" placeholder="No files Chosen"></textarea>

        <div class="fallback">
            <div class="well">
                <input name="files" type="file" multiple value="Files" id="ImageFile"  />
            </div>
            <input type="submit" value="Save Files" />
            @ViewBag.Message
        </div>
    </div>
}

the variable filename is always equal to "files" which is the name of the file input tag, but as mentioned, this always just gives back the first file selected. How do I make the loop go through all the files properly?

回答1:

It's possible that you're getting duplicate files back from the Request, try enumerating through them in a for loop and getting the file by it's index rather then fileName string;

for (int i = 0; i < Request.Files.Count; i++ )
{
    HttpPostedFileBase currentFile = Request.Files[i];
    //do your save etc here
}


标签: c# forms request