choose-image.js 1.9 KB
Newer Older
1
import { fileToUrl } from 'uni-platform/helpers/file'
2
import { updateElementStyle } from 'uni-shared'
3

fxy060608's avatar
fxy060608 已提交
4 5 6 7 8 9 10 11 12
const {
  invokeCallbackHandler: invoke
} = UniServiceJSBridge

let imageInput = null

const _createInput = function (options) {
  let inputEl = document.createElement('input')
  inputEl.type = 'file'
13 14 15 16 17
  updateElementStyle(inputEl, {
    'position': 'absolute',
    'visibility': 'hidden',
    'z-index': -999,
    'width': 0,
18 19 20
    'height': 0,
    'top': 0,
    'left': 0
21
  })
fxy060608's avatar
fxy060608 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  inputEl.accept = 'image/*'
  if (options.count > 1) {
    inputEl.multiple = 'multiple'
  }
  // 经过测试,仅能限制只通过相机拍摄,不能限制只允许从相册选择。
  if (options.sourceType.length === 1 && options.sourceType[0] === 'camera') {
    inputEl.capture = 'camera'
  }

  return inputEl
}

export function chooseImage ({
  count,
  // sizeType,
  sourceType
}, callbackId) {
  // TODO handle sizeType 尝试通过 canvas 压缩

  if (imageInput) {
    document.body.removeChild(imageInput)
    imageInput = null
  }

  imageInput = _createInput({
    count: count,
    sourceType: sourceType
  })
  document.body.appendChild(imageInput)

  imageInput.addEventListener('change', function (event) {
    const tempFiles = []
    const fileCount = event.target.files.length
    for (let i = 0; i < fileCount; i++) {
      const file = event.target.files[i]
57 58 59 60 61 62
      let filePath
      Object.defineProperty(file, 'filePath', {
        get () {
          filePath = filePath || fileToUrl(file)
          return filePath
        }
fxy060608's avatar
fxy060608 已提交
63
      })
64
      tempFiles.push(file)
fxy060608's avatar
fxy060608 已提交
65
    }
66
    const res = {
fxy060608's avatar
fxy060608 已提交
67
      errMsg: 'chooseImage:ok',
68 69 70
      get tempFilePaths () {
        return tempFiles.map(({ filePath }) => filePath)
      },
fxy060608's avatar
fxy060608 已提交
71
      tempFiles: tempFiles
72 73
    }
    invoke(callbackId, res)
fxy060608's avatar
fxy060608 已提交
74 75 76 77 78

    // TODO 用户取消选择时,触发 fail,目前尚未找到合适的方法。
  })

  imageInput.click()
79
}