dongtang1909 2019-06-02 11:56
浏览 125
已采纳

从库中选择多图像以发送到具有react-native的服务器

I try to send multi selected image and upload them to server. I can use react-native-image-picker to select one image and transfer this to base64 and save on state after that send it to the server. but I want multi-select from the gallery and to send them to server . may anyone help me to do that? first, how can I select the multi image and save data of that image to state? second, how can I send that state to save PHP server? third how to show that to the client in the app? in below you can see my cod. thanks

import React, { Component } from 'react';
import { StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, TextInput, Alert } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import {
  handleAndroidBackButton,
  removeAndroidBackButtonHandler
} from '../component/androidBackButton';
import RNFetchBlob from 'rn-fetch-blob';
import { ScrollView } from 'react-native-gesture-handler';
class testImage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ImageSource1: null,
      ImageSource2: null,
      ImageSource3: null,
      data: [],
      Image_TAG: ''
    };
  }
  componentDidMount() {
    handleAndroidBackButton(() => { this.props.navigation.navigate('AuthLoading') });
  }
  componentWillUnmount() {
    removeAndroidBackButtonHandler();
  }
  selectPhotoTapped(num) {
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,

      storageOptions: {
        skipBackup: true
      }
    };

    ImagePicker.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 {
        let source = { uri: response.uri };
        switch (num) {
          case '1':
            this.setState({

              ImageSource1: source,
              data: [...this.state.data, response.data],

            });
            break;
          case '2':
            this.setState({

              ImageSource2: source,
              data: [...this.state.data, response.data],

            });
            break;
          case '3':
            this.setState({

              ImageSource3: source,
              data: [...this.state.data, response.data],

            });
            break;

          default:
            break;
        }
      }
    });
  }
  uploadImageToServer2 = () => {

  alert(this.state.data)

  }
  uploadImageToServer = () => {

    RNFetchBlob.fetch('POST', 'http://192.168.2.102/Project/upload_image.php', {
      Authorization: "Bearer access-token",
      otherHeader: "foo",
      'Content-Type': 'multipart/form-data',
    }, [
      { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data[0] },
      { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data[1] },
      { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data[2] },
      { name: 'image_tag', data: this.state.Image_TAG }
      ]).then((resp) => {

        var tempMSG = resp.data;

        tempMSG = tempMSG.replace(/^"|"$/g, '');

        Alert.alert(tempMSG);

      }).catch((err) => {
        // ...
      })

  }
  render() {
    return (
      <ScrollView>
      <View style={styles.container}>

        <TouchableOpacity onPress={()=>this.selectPhotoTapped('1')}>

          <View style={styles.ImageContainer}>

            {this.state.ImageSource1 === null ? <Text>Select a Photo</Text> :
              <Image style={styles.ImageContainer} source={this.state.ImageSource1} />
            }

          </View>
          </TouchableOpacity>
          <TouchableOpacity onPress={()=>this.selectPhotoTapped('2')}>
          <View style={styles.ImageContainer}>

            {this.state.ImageSource2 === null ? <Text>Select a Photo</Text> :
              <Image style={styles.ImageContainer} source={this.state.ImageSource2} />
            }

          </View>
          </TouchableOpacity>
          <TouchableOpacity onPress={()=>this.selectPhotoTapped('3')}>
          <View style={styles.ImageContainer}>

            {this.state.ImageSource3 === null ? <Text>Select a Photo</Text> :
              <Image style={styles.ImageContainer} source={this.state.ImageSource3} />
            }

          </View>

        </TouchableOpacity>



 <TouchableOpacity onPress={()=>this.uploadImageToServer2()} activeOpacity={0.6} style={styles.button} >

<Text style={styles.TextStyle}> U2242D IMAGE TO SERVER </Text>

</TouchableOpacity>
        <TouchableOpacity onPress={this.uploadImageToServer} activeOpacity={0.6} style={styles.button} >

          <Text style={styles.TextStyle}> UPLOAD IMAGE TO SERVER </Text>

        </TouchableOpacity>

      </View>
      </ScrollView>
    );
  }
}

export default testImage;
const styles = StyleSheet.create({

  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#FFF8E1',
    paddingTop: 20
  },

  ImageContainer: {
    borderRadius: 10,
    width: 250,
    height: 250,
    borderColor: '#9B9B9B',
    borderWidth: 1 / PixelRatio.get(),
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#CDDC39',

  },

  TextInputStyle: {

    textAlign: 'center',
    height: 40,
    width: '80%',
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#028b53',
    marginTop: 20
  },

  button: {

    width: '80%',
    backgroundColor: '#00BCD4',
    borderRadius: 7,
    marginTop: 20
  },

  TextStyle: {
    color: '#fff',
    textAlign: 'center',
    padding: 10
  }

});
  • 写回答

1条回答 默认 最新

  • duandaishi9268 2019-06-03 07:25
    关注

    Please refer here, Multiple image selection is not supported by react-native-image-picker for IOS.

    I use react-native-image-crop-picker which supports multiple image selection for both android & ios

    import ImagePicker from 'react-native-image-crop-picker';//import
    
    ImagePicker.openPicker({
          includeBase64: true, // for base 64 string
          multiple: true,// To support multiple image selection
          quality: 1.0,
          maxWidth: 500,
          maxHeight: 500,
        }).then(image => {
            for (i = 0; i < image.length; i++) {
                this.state.images.push(image[i].data)//image[i].data=>base64 string
            }
    }
    uploadImageToServer = () => {
        this.state.images.map((data, key) => {
        RNFetchBlob.fetch('POST', 'http://192.168.2.102/Project/upload_image.php', {
            Authorization: "Bearer access-token",
            otherHeader: "foo",
            'Content-Type': 'multipart/form-data',
            },
            [{ name: 'image', filename: 'image.png', type: 'image/png', data: data },
            { name: 'image_tag', data: this.state.Image_TAG }]).then((resp) => {
                var tempMSG = resp.data;
                tempMSG = tempMSG.replace(/^"|"$/g, '');
                Alert.alert(tempMSG);
            }).catch((err) => {
            // ...
            })
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏