Search code examples
jqueryhtmlfile-upload

Get Filenames or Text from File Input multiple=multiple


I am trying to style up my input:file. The following SO question gets me 95% of the way there. The difference is that I am using the HTML5 multiple=multiple attribute.

How to style "input file" with CSS3 / Javascript?

JS

        $('#choose-files-button').click(function () {
            $(':file').trigger('click');
        });

        $(':file').change(function () {
            $this = $(this);
            $('#files-selected').text($this.val());
        })

Html

    @using (Html.BeginForm("Upload", "Manage", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <span id="choose-files-button" class="btn btn-info">Choose Files</span>
        <span id="files-selected"></span>
        <button class="pull-right btn btn-primary" type="submit">Upload</button>
        <div style="height:0; width:0;overflow:hidden;">
            <input type="file" name="files" id="files" multiple="multiple" value="Add Images" />
        </div>
    }

The Problem

The problem is that when the text of files-selected gets set it only shows one file name in Chrome. I haven't tested other browsers yet. It sets it to something like C:/Fakepath/asfd.jpg.When you just use the <input type="file" name="files" multiple="multiple" /> it says something like 3 files selected, which is the behavior I am trying to emulate.

Is there a way to get to that text, or get the number of files selected?


Solution

  • Use this.files.length where this is the file DOM element.

    $(':file').change(function () {
        $('#files-selected').text(this.files.length + " file selected");
    });
    

    Demo