3

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?

Community
  • 1
  • 1
Jason
  • 11,435
  • 24
  • 77
  • 131
  • possible duplicate of [Javascript. get number of files and their filenames from "input multiple" element?](http://stackoverflow.com/questions/6171013/javascript-get-number-of-files-and-their-filenames-from-input-multiple-elemen) – Ciro Santilli OurBigBook.com Nov 07 '14 at 22:44

3 Answers3

8

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

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

Demo

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
3

assuming you have the input element wrapped in a jQuery selector...

var file = $("input[type=file]");
var files = file[0].files;

files should be an array of files. From this you can get the number of files and the names of them. I'm not sure if this is webkit specific tho.

SynXsiS
  • 1,860
  • 10
  • 12
2

it works for me:

var f_img = $('#f_img')[0].files[0];

var n_img = f_img.name;

DEMO

Noe Alonso
  • 21
  • 1