Skip to content

Commit

Permalink
fix(image-picker): 将 FileReader 替换成 window.URL.createObjectURL
Browse files Browse the repository at this point in the history
  • Loading branch information
jimczj committed Dec 4, 2018
1 parent 2017bb9 commit 5274a0b
Showing 1 changed file with 32 additions and 25 deletions.
57 changes: 32 additions & 25 deletions src/components/image-picker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,40 +86,43 @@ export default class AtImagePicker extends AtComponent {
chooseFile () {
const { onChange, files, onFail, multiple } = this.props
const env = Taro.getEnv()
if (env === Taro.ENV_TYPE.WEB) {
this.fileInput.vnode.dom.click()
} else if (env === Taro.ENV_TYPE.WEAPP) {
// 微信小程序图片选择逻辑
Taro.chooseImage({
count: multiple ? 99 : 1
}).then(res => {
const targetFiles = res.tempFilePaths.map((path, i) => (
{
url: path,
file: res.tempFiles[i]
}
))
onChange(files.concat(targetFiles), 'add')
}).catch(onFail)
switch (env) {
case Taro.ENV_TYPE.WEB:
this.fileInput.vnode.dom.click()
break

case Taro.ENV_TYPE.WEAPP:
Taro.chooseImage({
count: multiple ? 99 : 1
}).then(res => {
const targetFiles = res.tempFilePaths.map(
(path, i) => ({
url: path,
file: res.tempFiles[i]
})
)
onChange(files.concat(targetFiles), 'add')
}).catch(onFail)
break

default:
console.log('暂未支持该环境')
break
}
}

handleImgChoose (event) {
// h5 图片监听逻辑
const { onChange, files, onFail } = this.props
const { onChange, files } = this.props
const targetFiles = event.target.files
if (targetFiles) {
for (let i = 0; i < targetFiles.length; i++) {
const reader = new FileReader()
reader.onload = function (e) {
if (!e.target.result) {
onFail(`Fail to get the ${i} image`)
}
files.push({ url: e.target.result, file: targetFiles[i] })
onChange(files, 'add')
}
reader.readAsDataURL(targetFiles[i])
files.push({
url: window.URL.createObjectURL(targetFiles[i]),
file: targetFiles[i]
})
}
onChange(files, 'add')
}
}

Expand All @@ -130,6 +133,10 @@ export default class AtImagePicker extends AtComponent {

handleRemoveImg (i) {
const { onChange, files } = this.props
const env = Taro.getEnv()
if (env === Taro.ENV_TYPE.WEB) {
window.URL.revokeObjectURL(files[i].url)
}
files.splice(i, 1)
onChange(files, 'remove', i)
}
Expand Down

0 comments on commit 5274a0b

Please sign in to comment.