js 文件与文件夹选择(已封装) - 戴向天

大家好!我叫戴向天

QQ群:602504799

/**
 * 使用方法:
 *  openLocalREsource(function(fileList){
 *    console.log('文件选择的结果=>',fileList);
 *  },'file');
 *
 *  openLocalREsource(function(fileList){
 *    console.log('文件夹选择的结果=>',fileList);
 *  },'folder');
 */

export default (change: (e: any) => void = (e) => {}, type = "file") => {
  const fileDom = document.querySelector(`#${type}InputDom`);

  // 限制类型
  if (["file", "folder"].indexOf(type) < 0) {
    return false;
  }

  // 判断结果,进行移除fileDom
  if (fileDom) {
    document.body.removeChild(fileDom);
  }

  const input = document.createElement("input") as HTMLInputElement;
  input.setAttribute("type", "file");
  input.setAttribute("multiple", "");
  input.id = type + "InputDom";
  // 判断是不是选择文件夹
  if (type === "folder") {
    input.setAttribute("webkitdirectory", "");
  }
  document.body.appendChild(input);
  input.onchange = function(e: any) {
    document.body.removeChild(input);
    change(e.target.files);
  };
  input.click();
};

猜你喜欢

转载自blog.csdn.net/weixin_41088946/article/details/115299646