从图库中选择多个图像以使用react-native发送到服务器

时间:2019-06-02 11:56:27

标签: php react-native

我尝试发送多个选定的图像并将其上传到服务器。我可以使用react-native-image-picker选择一个图像并将其传输到base64,然后将其发送到服务器后保存状态。但我想从库中进行多选并将其发送到server。谁能帮我做到这一点?首先,如何选择多张图像并保存该图像的数据以进行说明?第二,如何发送该状态以保存PHP服务器?第三如何在应用程序中向客户端显示?在下面,您可以看到我的鳕鱼。谢谢

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 个答案:

答案 0 :(得分:0)

请参阅here,不支持多张图像选择 react-native-image-picker  用于IOS。

我使用react-native-image-crop-picker,它支持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) => {
        // ...
        })
    })
}