LalA LalA - 4 months ago 10
ASP.NET (C#) Question

Upload files, show filenames on form immediately, BUT files get only uploaded to server om Form submit

I'm new to mvc and have a little trouble figuring out how to upload files to the server .

I have a form where the user enters name , address, city , upload files.

The user must be able to upload max 3 files . After the user has selected eg . 2 files , we display immediately files names on the form like this:

Uploaded files:
gif.dk
hitme.gif

BUT the selected files should ONLY be uploaded to the server after the form is submitted to server.

Answer

You can display a list of files to be uploaded by subscribing to the change event of the upload control in jQuery.

Controller:

public class UploaderController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Multiple(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
            if (file != null && file.ContentLength > 0)
            {
                file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
            }
        }
        return View("Index");
    }
}

View:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#uploadFiles').on("change", function () {
                var fileUpload = $(this);
                var files = fileUpload.context.files;

                $("#files").empty();
                $("#files").append("<h3>List of files to be uploaded:</h3>");

                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var name = file.name;

                    var div = "<div>File name:" + name + "</div>";
                    $("#files").append(div);
                }
            });
        });
    </script>
</head>
<body>
    @using (Html.BeginForm("Multiple", "Uploader", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <div id="multiple">
            <input id="uploadFiles" type="file" class="multiple" name="files" multiple />
        </div>
        <button class="btn btn-default">Upload</button>
        <div id="files">
        </div>
    }
</body>

Output:

Listing files to be uploaded using jQuery