Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

h5 端AtImagePicker组件多图上传失败 #4006

Closed
BinZhiZhu opened this issue Jul 29, 2019 · 1 comment
Closed

h5 端AtImagePicker组件多图上传失败 #4006

BinZhiZhu opened this issue Jul 29, 2019 · 1 comment

Comments

@BinZhiZhu
Copy link

问题描述
h5端AtImagePicker组件多图上传失败,只能上传第一张图片,第二次上传时候,Input组件的 refFileInput 并没有模拟点击成功,获取不到Event。

复现步骤

组件代码:

/* eslint-disable no-nested-ternary */
import Taro from '@tarojs/taro'
import { View, Input, Image } from '@tarojs/components'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import defaultFunc from '@/utils/defaultFunc'
import AtFontIcon from '@/taro-ui/components/font-icon'
import isRNApp from '@/utils/isRNApp'
import './index.scss'

// 生成 jsx 二维矩阵
const generateMatrix = (files, col, showAddBtn) => {
  const matrix = []
  const length = showAddBtn ? files.length + 1 : files.length
  const row = Math.ceil(length / col)
  for (let i = 0; i < row; i++) {
    if (i === row - 1) {
      // 最后一行数据加上添加按钮
      const lastArr = files.slice(i * col)
      if (lastArr.length < col) {
        if (showAddBtn) {
          lastArr.push({ type: 'btn' })
        }
        // 填补剩下的空列
        for (let j = lastArr.length; j < col; j++) {
          lastArr.push({ type: 'blank' })
        }
      }
      matrix.push(lastArr)
    } else {
      matrix.push(files.slice(i * col, (i + 1) * col))
    }
  }
  return matrix
}

class AtImagePicker extends Taro.Component {

  static options = {
    addGlobalClass: true
  };

  static defaultProps = {
    className: '',
    customStyle: '',
    files: [],
    mode: 'aspectFill',
    showAddBtn: true,
    itemStyle: {},
    chooseBtnIcon:'upload',
    multiple: false,
    length: 4,
    onChange: defaultFunc,
    onImageClick: defaultFunc,
    onFail: defaultFunc,
  };

  static propTypes = {
    className: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.array
    ]),
    customStyle: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object
    ]),
    files: PropTypes.array,
    mode: PropTypes.oneOf([
      'scaleToFill',
      'aspectFit',
      'aspectFill',
      'widthFix',
      'top',
      'bottom',
      'center',
      'left',
      'right',
      'top left',
      'top right',
      'bottom left',
      'bottom right'
    ]),
    itemStyle:PropTypes.object,
    chooseBtnIcon:PropTypes.string,
    showAddBtn: PropTypes.bool,
    multiple: PropTypes.bool,
    length: PropTypes.number,
    onChange: PropTypes.func,
    onImageClick: PropTypes.func,
    onFail: PropTypes.func,
  }

  chooseFile () {
    console.log('chooseFile');
    const { onChange, files, onFail, multiple } = this.props

    if (process.env.TARO_ENV === 'rn') {
      console.log('RN开发中');
      // TODO
      Taro.chooseImage({
        count: 1,
      }).then(() => {
        return
      }).catch(onFail)
      return;
    }

    if (process.env.TARO_ENV === 'weapp') {
      Taro.chooseImage({
        count: multiple ? 99 : 1
      }).then(res => {
        const targetFiles = res.tempFilePaths.map(
          (path, i) => ({
            url: path,
            file: res.tempFiles[i]
          })
        )
        return onChange(files.concat(targetFiles), 'add')
      }).catch(onFail);
      return;
    }

    if (process.env.TARO_ENV === 'h5') {
      this.fileInput.vnode.dom.click();
      return;
    }

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

  handleImgChoose = (event) => {
    console.log('h5 图片监听逻辑 handleImgChoose', event);
    const { onChange, files } = this.props
    const targetFiles = event.target.files
    if (targetFiles) {
      for (let i = 0; i < targetFiles.length; i++) {
        files.push({
          url: window.URL.createObjectURL(targetFiles[i]),
          file: targetFiles[i]
        })
      }
      onChange && onChange(files, 'add')
    }
    // fix 上传第二次不能选择同一文件
    event.target.value = ''
  };

  handleImageClick (i) {
    const { onImageClick, files } = this.props
    onImageClick && onImageClick(i, files[i])
  }

  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 && onChange(files, 'remove', i)
  }

  refFileInput = node => {
    this.fileInput = node
  };

  render () {
    const {
      className,
      customStyle,
      files,
      mode,
      multiple,
      length,
      showAddBtn,
      chooseBtnIcon,
      itemStyle,
    } = this.props
    // 行数
    const matrix = generateMatrix(files, length, showAddBtn)

    return (
      <View
        className={
          classNames('at-image-picker', className)
        }
        style={customStyle}
      >
        {!isRNApp() && (
          <Input
            className='at-image-picker__file-input'
            ref={this.refFileInput}
            type='file'
            accept='image/*'
            multiple={multiple ? 'multiple' : ''}
            onChange={this.handleImgChoose}
          />
        )}
        {
          matrix.map((row, i) => (
            <View
              key={`${i}`}
              className='at-image-picker__flex-box'
            >
              {
                row.map((item, j) => (
                  item.url
                    ? <View
                      className='at-image-picker__flex-item'
                      key={`${i}-${j}`}
                    >
                      <View className='at-image-picker__item'>

                        {!item.fixed && (
                          <View
                            className='at-image-picker__remove-btn'
                            onClick={this.handleRemoveImg.bind(this, (i * length) + j)}
                          >
                            <AtFontIcon
                              name='roundclosefill'
                              color='#fff'
                              size={32}
                            />
                          </View>
                        )}

                        <Image
                          mode={mode}
                          onClick={this.handleImageClick.bind(this, (i * length) + j)}
                          className='at-image-picker__preview-img'
                          src={item.url}
                        />
                      </View>
                    </View>
                    : item.type === 'blank'
                      ? <View
                        className='at-image-picker__flex-item'
                        key={`${i}-${j}`}
                      />
                      : <View
                        className='at-image-picker__flex-item'
                        onClick={this.chooseFile.bind(this)}
                        style={itemStyle}
                      >
                        <View className='at-image-picker__item at-image-picker__choose-btn'>
                          <AtFontIcon
                            name={chooseBtnIcon}
                            className='at-image-picker__upload-icon'
                          />
                        </View>
                      </View>
                ))
              }
            </View>
          ))
        }
      </View>
    )
  }
}

export default AtImagePicker;

期望行为

期望h5端可以多图上传成功

报错信息

image

系统信息

👽 Taro v1.3.10
Taro CLI 1.3.10 environment info:
System:
OS: macOS 10.14.6
Shell: 5.3 - /bin/zsh
Binaries:
Node: 11.10.0 - /usr/local/bin/node
Yarn: 1.15.2 - /usr/local/bin/yarn
npm: 6.7.0 - /usr/local/bin/npm
npmPackages:
@tarojs/async-await: 1.3.10 => 1.3.10
@tarojs/cli: 1.3.10 => 1.3.10
@tarojs/components: 1.3.10 => 1.3.10
@tarojs/components-qa: 1.3.10 => 1.3.10
@tarojs/components-rn: 1.3.10 => 1.3.10
@tarojs/plugin-babel: 1.3.10 => 1.3.10
@tarojs/plugin-csso: 1.3.10 => 1.3.10
@tarojs/plugin-sass: 1.3.10 => 1.3.10
@tarojs/plugin-uglifyjs: 1.3.10 => 1.3.10
@tarojs/redux: 1.3.10 => 1.3.10
@tarojs/redux-h5: 1.3.10 => 1.3.10
@tarojs/rn-runner: 1.3.10 => 1.3.10
@tarojs/router: 1.3.10 => 1.3.10
@tarojs/taro: 1.3.10 => 1.3.10
@tarojs/taro-alipay: 1.3.10 => 1.3.10
@tarojs/taro-h5: 1.3.10 => 1.3.10
@tarojs/taro-qq: 1.3.10 => 1.3.10
@tarojs/taro-quickapp: 1.3.10 => 1.3.10
@tarojs/taro-redux-rn: 1.3.10 => 1.3.10
@tarojs/taro-rn: 1.3.10 => 1.3.10
@tarojs/taro-router-rn: 1.3.10 => 1.3.10
@tarojs/taro-swan: 1.3.10 => 1.3.10
@tarojs/taro-tt: 1.3.10 => 1.3.10
@tarojs/taro-weapp: 1.3.10 => 1.3.10
@tarojs/webpack-runner: 1.3.10 => 1.3.10
eslint-config-taro: 1.3.10 => 1.3.10
eslint-plugin-taro: 1.3.10 => 1.3.10
nerv-devtools: ^1.4.3 => 1.4.3
nervjs: ^1.4.3 => 1.4.3
react: 16.3.1 => 16.3.1
react-native: 0.55.4 => 0.55.4
npmGlobalPackages:
typescript: 3.5.2

补充信息

refFileInput 模拟点击Click 问题

@taro-bot
Copy link

taro-bot bot commented Jul 29, 2019

欢迎提交 Issue~

如果你提交的是 bug 报告,请务必遵循 Issue 模板的规范,尽量用简洁的语言描述你的问题,最好能提供一个稳定简单的复现。🙏🙏🙏

如果你的信息提供过于模糊或不足,或者已经其他 issue 已经存在相关内容,你的 issue 有可能会被关闭。

Good luck and happy coding~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant