In JavaScript is it possible to launch a file browser dialog programmatically?

前端 未结 5 1565
耶瑟儿~
耶瑟儿~ 2020-12-15 23:18

Instead of using the tag I\'d like to have a button that launches a file browser dialog.

My first thought was to have a hidd

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 00:06

    I'd rather avoid transparency tricks.

    This worked for me (uses jQuery):

    $("#upload-box").change(function(){
        $("#upload-click-handler").val($(this).val());
    });
    $("#upload-click-handler").click(function(){
        $("#upload-box").click();
    });
    

    And the HTML:

    
    
    

    It creates a text input, and a hidden upload input, and patches (=routes) the click on the text input to the hidden file input.

    When a file is selected, it will write back the name of the file in the text input, in line with what most users would expect from the interface.

    Should work on FF, Chrome, IE9 and +. I didn't test it on IE8.

    Here's a jsfiddle. Thank you for upvoting my answer if you like it.

提交回复
热议问题