0

I have a simple file upload js that allows me to use a stylized button rather than the traditional form element UI. It basically hides the fileElement and hooks it up to my stylized button. Issue I have now is that I am missing the traditional "name of file" that was picked.

 <input type="file" class="fileElem pull-right" id="chooseFile" multiple onchange="handleFiles(this.files)">
 <button class="fileSelect pull-right" id="selectFile">Choose File</button>


 <script type="text/javascript">
    function click(el) {
            // Simulate click on the element.
            var evt = document.createEvent('Event');
            evt.initEvent('click', true, true);
            el.dispatchEvent(evt);
    }

    document.querySelector('#selectFile').addEventListener('click', function(e) {
            var fileInput = document.querySelector('#chooseFile');
            //click(fileInput); // Simulate the click with a custom event.
            fileInput.click(); // Or, use the native click() of the file input.
    }, false);

    function handleFiles(files) {
            alert('Well done!');
    }

ndesign11
  • 1,734
  • 6
  • 20
  • 36

1 Answers1

1

You can iterate through the fileList object and read the name property of each file.

// Assuming you want to populate an `ul`/`ol` element on change event
function handleFiles(files) {
    var list = [].slice.call(files).map(function(file) {
        return '<li>' + file.name + '</li>';
    }).join('');

    document.getElementById('anUL').innerHTML = list;
}

http://jsfiddle.net/5x7k5s14/

Ram
  • 143,282
  • 16
  • 168
  • 197