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) => {
            // ...
            })
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境