react-native多图上传 react-native-image-picker图片上传之多个上传图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z93701081/article/details/83587175

话不多说 直接贴代码, 如有疑问 下方留言或者发邮箱

引入需要的组件
import ImagePicker2 from 'react-native-image-picker';
import RNHeicConverter from 'react-native-heic-converter';
// RNHeicConverter图片转换 IOS11之后 有HEIC图片需要转换 不然显示不出来 
clas Page extends Component {
  constructor(props) {
    super(props);
    this.state = {
      files: [],
      title: "",
      content: "",
      src: [],
      selectMap: new Map(),
    };
    this.srcArr = []
  }


<View style={{marginHorizontal: 10, marginVertical: 10, flexDirection: 'row', flexWrap: 'wrap'}}>
            {
              temp ? temp.map((v, i) => {
                return (
                  <View
                    style={{
                      flexDirection: 'row',
                      marginRight: 10,
                      marginBottom: 10,
                      position: 'relative'
                    }}
                    key={i}
                  >
                    <Image
                      roundAsCircle={true}
                      style={{
                        height: 70,
                        width: 70,
                        borderRadius: 10
                      }} source={{uri: v}}
                    />
                    <TouchableOpacity
                      style={{
                        position: 'absolute',
                        top: 0,
                        right: 0
                      }}
                      onPress={()=>{
                        let newMap = this.state.selectMap
                        let temp = [...this.state.selectMap.values()];
                        let temp2 = [...this.state.selectMap.keys()];
                        newMap.delete(temp2[i], temp[i])
                        this.setState({
                          selectMap:newMap
                        })
                      }}
                    >
                      <Image
                        style={{
                          height: 18,
                          width: 18
                        }}
                        source={require('../images/删除图片.png')}
                      />
                    </TouchableOpacity>
                  </View>

                )
              }) : null
            }
            {
              temp.length === 4 ?
                <Tip tipMsg="*注:最多上传四张图片哦"/>
                :
                <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
                  <View style={[{marginBottom: 20}]}>
                    <Image
                      style={{width: 70, height: 70}}
                      source={require('../images/增加按钮.png')}
                    />
                  </View>
                </TouchableOpacity>
            }
          </View>
selectPhotoTapped() {
    const options = {
      title: '选择图片',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '选择照片',
      cameraType: 'back',
      mediaType: 'photo',
      videoQuality: 'medium',  // 图片质量
      durationLimit: 10,  // 
      maxWidth: 500, // 图片大小
      maxHeight: 500, // 图片大小
      quality: 0.8,
      angle: 0,
      allowsEditing: false,
      noData: false,
      storageOptions: {
        skipBackup: true
      }
    };

    ImagePicker2.showImagePicker(options, (response) => {
      // console.log('Response = ', response);
      if (response.didCancel) {
        console.log('User cancelled photo picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {
        Toast.loading('上传中...')
        console.log(response)
        let source = {}
        if (Platform.OS === 'ios' && (response.fileName.endsWith('.heic') || response.fileName.endsWith('.HEIC'))) {
          RNHeicConverter.convert({ path: response.origURL }).then((data) => {
            const { success, path, error } = data

            if(!error && success && path) {

              let name = response.fileName

              name = name.replace(".heic", ".jpg")

              name = name.replace(".HEIC", ".jpg")

              source = {uri: path, name}
              console.log(source)
            } else {
              Toast.show('图片上传失败!')
            }
          })
        } else {
          source = {uri: response.uri, type: response.type, name: response.fileName}
          console.log(source)
        }

        upload("/api/UploadImage/uploadDisplayImage", response)
          .then(param => {
            const responseData = JSON.parse(param.data)
            console.log(response)
            console.log(param)
            let newMap = this.state.selectMap
            this.srcArr.push(responseData.data)
            newMap.set(response.fileName, response.uri)
            Toast.info("上传成功",0.5)
            this.setState({
              selectMap: newMap,
              src: this.srcArr
            });
          })
          .catch(err => {
            console.log(err)
            Toast.info("上传失败",0.5);
            this.setState({
              files: []
            });
          })
      }
    })
  }
  }
 submitFeedback = () => { // 提交到服务端
    const {navigation: {state}, loginSession} = this.props;
    const {token, uuid} = loginSession
    const {title, content, files, concat, src} = this.state;
    console.log(this.state)
    if (title.length === 0 || content.length === 0) {
      Toast.info("请填写标题和内容");
      return;
    }
    if (src.length === 0) {
      Toast.info("请上传图片")
      return;
    }
    this.props.dispatch({  // 
      type: 'photoFeedBackPage/MemberDisplayAdd',
      payload: {
        token,
        uuid,
        title,
        content,
        display_img: src.join(';')
      }
    })
  }

猜你喜欢

转载自blog.csdn.net/z93701081/article/details/83587175