Multiple file uploader in MVC that works with IE

Uploading multiple files is a common task in web programming. HTML 4/5 provides us with the “multiple” attribute to do this in HTML 4/5. Unfortunately, this functionality is not supported in IE. Eventhough IE is a terrible, horrible browser, it is still being used by a big portion of customer, particularly the public sector. Besides, it’s generally a web’s programmer responsibility to make sure that his/her code support multiple browsers.

To accomplish this function, I decided to wrap the file list in a div and dynamically add more <input> tag after user selected an item. A remove button is also added to make sure that the user can remove the selection later on (unless if the item is the last node). The function can (should!) be modified to accept a string that indicate the id of the div, and accept a name string so it can be used in a library, etc but you get the rough idea 😉

HTML

Do not forget to add the form’s enctype!

@using (Html.BeginForm("Save", "ViewModel", FormMethod.Post, new { enctype = "multipart/form-data"})) {
}

File list :

</pre>
<div class="editor-field" id="fileList"><input id="file0" type="file" name="files" onchange="createInputTags(this)" />
 <button onclick="remove(this,'file0')" type="button">Remove</button></div>
<pre>

JavaScript

  function createInputTags(data) {
        var num = document.getElementById('fileList').getElementsByTagName('input').length;
        $("#fileList").append("
<input id="file&quot; + num + &quot;" type="file" name="files" onchange="createInputTags(this)" /><button onclick="\&quot;remove(this,'file&quot;" type="button">Remove</button>");
    }

    function remove(sender, elementId) {
        var num = document.getElementById('fileList').getElementsByTagName('input').length;
        element = document.getElementById(elementId);
        if (num > 1) {
            element.parentNode.removeChild(element);
            sender.parentNode.removeChild(sender);
        } else {
            //clear?
        }
    }

Accessing the files in mvc


public ActionResult Save(IssueModel issuemodel,IEnumerable files)
{
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: