Sanju Rao
Sanju Rao

Reputation: 331

Not able to upload multiple files with IEnumerable<HttpPostedFileBase>

I have scenario where the user selects 4 images to upload and I need to bind this four files to my model and save into the folder. but the problem I am facing is my model when reaches to action method it will be null.

My View :

@using(@Html.BeginForm("fileUpload","Home",FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<div>
    <h1>Auto Upload</h1>
</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file1" , Type = "file" })</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file2" , Type = "file" })</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file3" , Type = "file" })</div>
<div>@Html.TextBoxFor(m => m.MyFile, new { id = "file4" , Type = "file" })</div>
<input type ="submit" name ="submit" />
}

My Model :

public class MyModel
    {
        public IEnumerable<HttpPostedFileBase> MyFile { get; set; }
    }

Controller : When I click on submit in my controller's fileUpload method I get files = null.

        [HttpPost]
        public void fileUpload(IEnumerable<HttpPostedFileBase> files)
        {
            string s = "upload";
        }

I am very new to file upload things compared to my usual work.

Upvotes: 1

Views: 3945

Answers (1)

dom
dom

Reputation: 6842

You're displaying the same textbox four times with the same name but a different id, the model binder has no idea you're trying to post a collection named files. Also don't use the TextBoxFor helper here, nothing wrong with using plain old HTML elements in this situation.

@using (@Html.BeginForm("fileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <label for="file1">File :</label>
    <input type="file" name="files" id="file1" />

    <label for="file2">File :</label>
    <input type="file" name="files" id="file2" />

    <label for="file3">File :</label>
    <input type="file" name="files" id="file3" />

    <label for="file4">File :</label>
    <input type="file" name="files" id="file4" />

    <input type="submit" value="Upload" />
}

Your controller method signature then stays intact, but you'll see the files collection is properly filled.

[HttpPost]
public void fileUpload(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        // Validate size (in bytes), set your limit accordingly
        if (file.ContentLength > 0  && file.ContentLength <= 2097152)
        {
            // Do something with your files
        }
    }
}

The important thing to keep in mind is that model binding works based on the name attribute given to form elements. The way you had it, inputs were rendered something like <input name="MyFile"> so when posted back to the server, there's nothing indicating that it should bind to a collection called files.

Upvotes: 3

Related Questions