How to open select file dialog via js?

前端 未结 9 1705
伪装坚强ぢ
伪装坚强ぢ 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:16

    READY TO USE FUNCTION (using Promise)

    /**
     * Select file(s).
     * @param {String} contentType The content type of files you wish to select. For instance "image/*" to select all kinds of images.
     * @param {Boolean} multiple Indicates if the user can select multiples file.
     * @returns {Promise} A promise of a file or array of files in case the multiple parameter is true.
     */
    function (contentType, multiple){
        return new Promise(resolve => {
            let input = document.createElement('input');
            input.type = 'file';
            input.multiple = multiple;
            input.accept = contentType;
    
            input.onchange = _ => {
                let files = Array.from(input.files);
                if (multiple)
                    resolve(files);
                else
                    resolve(files[0]);
            };
    
            input.click();
        });
    }
    

    TEST IT

    // Content wrapper element
    let contentElement = document.getElementById("content");
    
    // Button callback
    async function onButtonClicked(){
        let files = await selectFile("image/*", true);
        contentElement.innerHTML = files.map(file => ``).join('');
    }
    
    // ---- function definition ----
    function selectFile (contentType, multiple){
        return new Promise(resolve => {
            let input = document.createElement('input');
            input.type = 'file';
            input.multiple = multiple;
            input.accept = contentType;
    
            input.onchange = _ => {
                let files = Array.from(input.files);
                if (multiple)
                    resolve(files);
                else
                    resolve(files[0]);
            };
    
            input.click();
        });
    }
    
    

提交回复
热议问题