Hoan Dang
Hoan Dang

Reputation: 376

Multiple files with single fileupload issues in ASP.NET MVC 3

I have one fileupload that can select multiple files. But the server side only receives the last selection when I click submit. For instance, first time I select 2 images, then 3 images,totally 5 images. After submitting, server catchs only 3 last images. My idea is putting all the images into one hidden input, then server will get data from hidden input. But I don't know how to put them in hidden input.

My question is how to put data image into a hidden input ?

Upvotes: 0

Views: 3318

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could clone the actual file input. Here's an example:

Model:

public class MyViewModel
{
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

<script type="text/javascript">
    $(function () {
        $(':file').change(function () {
            if (this.files.length > 0) {
                var real = $(this);
                var cloned = real.clone(true);
                real.hide();
                cloned.insertAfter(real);
                real.appendTo('form');
            }
        });
    });
</script>

@Html.TextBoxFor(x => x.Files, new { type = "file", multiple = "multiple", value = "", id = (string)null })

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <button type="submit">Upload</button>
}

The idea is that the original file input is outside of the form. Then everytime the user performs a file selection we are cloning the field and inserting it into the form as a hidden file input. When the form is submitted all files will be uploaded to the server.

A further improvement of the script would obviously be to provide some visual indication to the user of the number of files that are going to be uploaded to the server.

Upvotes: 1

Related Questions