jQuery trigger file input

后端 未结 21 1566
梦如初夏
梦如初夏 2020-11-22 08:49

Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

$(\'#fileinput\').trigger(\'click\');   
相关标签:
21条回答
  • 2020-11-22 09:16

    adardesign nailed it regarding the file input element being ignored when it is hidden. I also noticed many people shifting element size to 0, or pushing it out of bounds with positioning and overflow adjustments. These are all great ideas.
    An alternative way that also seems to work perfectly well is to just set the opacity to 0. Then you can always just set the position to keep it from offsetting other elements as hide does. It just seems a little unnecessary to shift an element nearly 10K pixels in any direction.

    Here's a little example for those who want one:

    input[type='file']{
        position:absolute;
        opacity:0;
        /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
        -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
        /* For IE5 - 7 */
        filter: alpha(opacity=0);
    }
    
    0 讨论(0)
  • 2020-11-22 09:16

    Try this, it's a hack. the Position:absolute is for Chrome and trigger('change') is for IE.

    var hiddenFile = $("<input type=\"file\" name=\"file\" id=\"file1\" style=\"position:absolute;left:-9999px\" />");
    $('body').append(hiddenFile);
    
    $('#aPhotoUpload').click(function () {
        hiddenFile.trigger('click');
        if ($.browser.msie)
            hiddenFile.trigger('change');
    });
    
    hiddenFile.change(function (e) {
        alert('TODO');
    });
    
    0 讨论(0)
  • 2020-11-22 09:19

    That's on purpose and by design. It's a security issue.

    0 讨论(0)
  • 2020-11-22 09:20

    Just for the sake of curiosity, you can do something like you want by dynamically creating an upload form and input file, without adding it to the DOM tree:

    $('.your-button').on('click', function() {
        var uploadForm = document.createElement('form');
        var fileInput = uploadForm.appendChild(document.createElement('input'));
    
        fileInput.type = 'file';
        fileInput.name = 'images';
        fileInput.multiple = true;
    
        fileInput.click();
    });
    

    No need to add the uploadForm to the DOM.

    0 讨论(0)
  • 2020-11-22 09:20

    This is probably the best answer, keeping in mind the cross browser issues.

    CSS:

    #file {
      opacity: 0;
      width: 1px;
      height: 1px;
    }
    

    JS:

    $(".file-upload").on('click',function(){
       $("[name='file']").click();
    });
    

    HTML:

    <a class="file-upload">Upload</a>
    <input type="file" name="file">
    
    0 讨论(0)
  • 2020-11-22 09:22

    You can use LABEL element ex.

    <div>
        <label for="browse">Click Me</label>
        <input type="file" id="browse" name="browse" style="display: none">//
    </div>

    This will trigger the input file

    0 讨论(0)
提交回复
热议问题