How to open select file dialog via js?

前端 未结 9 1672
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 06:16
$(\'#id\').click();

It doesn\'t work on Chrome 26 on Mac OS.

The problem actually is creation "upload" widget that can be integrated in

相关标签:
9条回答
  • 2021-01-30 07:18

    To expand on the answer from 'levi' and to show how to get the response from the upload so you can process the file upload:

    selectFile(event) {
        event.preventDefault();
    
        file_input = document.createElement('input');
        file_input.addEventListener("change", uploadFile, false);
        file_input.type = 'file';
        file_input.click();
    },
    
    uploadFile() {
        let dataArray = new FormData();
        dataArray.append('file', file_input.files[0]);
    
        // Obviously, you can substitute with JQuery or whatever
        axios.post('/your_super_special_url', dataArray).then(function() {
            //
        });
    }
    
    0 讨论(0)
  • 2021-01-30 07:19

    In HTML only:

    <label>
      <input type="file" name="input-name" style="display: none;" />
      <span>Select file</span>
    </label>
    

    Edit: I hadn't tested this in Blink, it actually doesn't work with a <button>, but it should work with most other elements–at least in recent browsers.

    Check this fiddle with the code above.

    0 讨论(0)
  • 2021-01-30 07:21

    First Declare a variable to store filenames (to use them later):

    var myfiles = [];
    

    Open File Dialog

    $('#browseBtn').click(function() {
        $('<input type="file" multiple>').on('change', function () {
            myfiles = this.files; //save selected files to the array
            console.log(myfiles); //show them on console
        }).click();
    });
    

    i'm posting it, so it may help someone because there are no clear instructions on the internet to how to store filenames into an array!

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