How to open select file dialog via js?

前端 未结 9 1714
伪装坚强ぢ
伪装坚强ぢ 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 06:59

    function promptFile(contentType, multiple) {
      var input = document.createElement("input");
      input.type = "file";
      input.multiple = multiple;
      input.accept = contentType;
      return new Promise(function(resolve) {
        document.activeElement.onfocus = function() {
          document.activeElement.onfocus = null;
          setTimeout(resolve, 500);
        };
        input.onchange = function() {
          var files = Array.from(input.files);
          if (multiple)
            return resolve(files);
          resolve(files[0]);
        };
        input.click();
      });
    }
    function promptFilename() {
      promptFile().then(function(file) {
        document.querySelector("span").innerText = file && file.name || "no file selected";
      });
    }
    
    

提交回复
热议问题