发布于 4年前

纯 js 实现选择文件

// 使用默认选项(仅选择图片,可多选)
let imageFiles = await selectFile()

// 自定义选项(仅选择图片,不可多选)
let imageFile = await selectFile({
    multiple: false
})

// 自定义选项(仅选择文本,可多选)
let txtFiles = await selectFile({
    accept: 'text/plain'
})

// 自定义选项(可选择任意文件类型,可多选)
let files = await selectFile({
    accept: ''
})

/**
 * 选择文件
 */
function selectFile(_options) {
  return new Promise((res, rej) => {
    let options = {
      accept: 'image/*',
      multiple: true
    }

    if (_options) {
      options.accept = _options.accept
      options.multiple = _options.multiple
    }

    const el = document.createElement('input')
    el.type = 'file'
    el.accept = options.accept
    el.multiple = options.multiple
    el.addEventListener('change', _ => {
      if (options.multiple) {
        res(el.files)
      } else {
        res(el.files[0])
      }
    })
    el.click()
  })
}
©2020 edoou.com   京ICP备16001874号-3