0

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 ?

1 Answer 1

1

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.

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

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.