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

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

let imageInput = null

const _createInput = function (options) {
  let inputEl = document.createElement('input')
  inputEl.type = 'file'
12
  inputEl.style = 'position: absolute;visibility: hidden;z-index: -999;width: 0;height: 0;'
fxy060608's avatar
fxy060608 已提交
13 14 15 16 17 18 19 20 21 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
  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 tempFilePaths = []
    const tempFiles = []
    const fileCount = event.target.files.length
    for (let i = 0; i < fileCount; i++) {
      const file = event.target.files[i]
49
      const filePath = fileToUrl(file)
fxy060608's avatar
fxy060608 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

      tempFilePaths.push(filePath)
      tempFiles.push({
        path: filePath,
        size: file.size
      })
    }

    invoke(callbackId, {
      errMsg: 'chooseImage:ok',
      tempFilePaths: tempFilePaths,
      tempFiles: tempFiles
    })

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

  imageInput.click()
68
}