Search code examples
twitter-bootstrapfileapi

Invoke the FileAPI from a Bootstrap button


This is my code for invoking the FileAPI, to upload images to the client.

   //Import SVG does not use click triggers as other functions do.

var file = document.getElementById('tool-importSVG');
        file.addEventListener('click', function (event) {
            var files = event.target.files;
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                if (file.type.match('svg')) {
                    project.importSVG(file, function(item) {
                        console.log(item);
                    });
                }
            }
        });
//End of SVG import

and this is the HTML

<li><a href="#"  id="tool-importSVG" >Import SVG</a></li>

Is there a way to use a BUTTON instead to invoke the FileAPI? E.g a Bootstrap button.


Solution

  • As per your code, you have var file = document.getElementById('tool-importSVG');

    But inside the event listening function, again you are using var file = files[i]; It means you are redefining the file variable. I would suggest you to rename that variable.

    Now coming to your question:

    You can use a bootstrap button to upload files:

    <span class="btn btn-success fileinput-button">
             <i class="glyphicon glyphicon-plus"></i>
             <span>Add files...</span>
             <input type="file" name="files[]" multiple="">
     </span>
    

    It will look like below:

    enter image description here

    CSS:

     .fileinput-button input {
           position: absolute;
           opacity: 0;
           -ms-filter: 'alpha(opacity=0)';
           direction: ltr;
           cursor: pointer;
           margin-top: -25px 0 0 0;
        }
    

    You can change the color as you want :)