choose-image.js 1.3 KB
Newer Older
1
import { fileToUrl } from 'uni-platform/helpers/file'
2
import _createInput from './create_input'
3

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

let imageInput = null

export function chooseImage ({
  count,
  // sizeType,
13 14
  sourceType,
  extension
fxy060608's avatar
fxy060608 已提交
15 16 17 18 19 20 21 22 23
}, callbackId) {
  // TODO handle sizeType 尝试通过 canvas 压缩

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

  imageInput = _createInput({
24 25 26 27
    count,
    sourceType,
    extension,
    type: 'image'
fxy060608's avatar
fxy060608 已提交
28 29 30 31 32 33 34 35
  })
  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]
36
      let filePath
Q
qiang 已提交
37
      Object.defineProperty(file, 'path', {
38 39 40 41
        get () {
          filePath = filePath || fileToUrl(file)
          return filePath
        }
fxy060608's avatar
fxy060608 已提交
42
      })
43
      if (i < count) tempFiles.push(file)
fxy060608's avatar
fxy060608 已提交
44
    }
45
    const res = {
fxy060608's avatar
fxy060608 已提交
46
      errMsg: 'chooseImage:ok',
47
      get tempFilePaths () {
Q
qiang 已提交
48
        return tempFiles.map(({ path }) => path)
49
      },
fxy060608's avatar
fxy060608 已提交
50
      tempFiles: tempFiles
51 52
    }
    invoke(callbackId, res)
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57

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

  imageInput.click()
58
}