Реагируйте на загрузку собственного изображения в виде данных формы - PullRequest
0 голосов
/ 25 июня 2019

Формы данных почтальона работают отлично, но они возвращаются после ошибки http 500. что не так с этим блоком.


Ответ {тип: «по умолчанию», статус: 500, ок: ложь, текст состояния: undefined, headers: Headers,…} headers: Headers {map: {…}} ok: falsestatus: 500statusText: undefinedtype: "default" url: "http://cupdes.com/api/v1/create-user"_bodyInit:" "_bodyText: "" proto : Объект "rtghj"

import React, {Component} from 'react';
import {Platform, StyleSheet,View,Image,ScrollView,TextInput,KeyboardAvoidingView,TouchableOpacity,TouchableHighlight,AsyncStorage,} from 'react-native';
import { Container, Header, Content, Button, Text,Input, Label,Item,Form, } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-picker';

export default class SignUp extends Component {
  constructor(){
    super();
    this.state = {
      email: "",
      name: "",
      password: "",
      photo: null ,

      errors: [],
      showProgress: false,
    }
}
handleChoosePhoto = () => {
  const options = {
    noData: true,
  };
  ImagePicker.launchImageLibrary(options, response => {
    if (response.uri) {
      this.setState({ photo: response });
    }
  });
};

onPressSubmitButton() {
  console.log("Image ",this.state.photo,this.state.email,this.state.password,this.state.name)
  this.onFetchLoginRecords();
} 

async onFetchLoginRecords() {



const createFormData = () => {
  var data = new FormData();

  data.append("image", {
    name: this.state.photo.fileName,
    type: this.state.photo.type,
    uri:
      Platform.OS === "android" ? this.state.photo.uri : this.state.photo.uri.replace("file://", "")
  });
  data.append('name', this.state.name);
  data.append('password',this.state.password);
  data.append('email', this.state.email);
  console.log("aaaa",data);
  return data;
};


try {
  let response = await fetch(

   'http://cupdes.com/api/v1/create-user',
   {
     method: 'POST',
     headers: {
      'X-AUTH-TOKEN': 'Px7zgU79PYR9ULEIrEetsb',
      'Content-Type': 'multipart/form-data'

     },
    body:createFormData() 

  }
 )
 .then((response) => {
 console.log(response,"rtghj") 
 this.setState({ photo: null });
 if (JSON.parse(response._bodyText) === null) {
  alert("Internal server error!!!");
 }else{
  if (JSON.parse(response._bodyText).success === "true") {
    this.props.navigation.navigate('loading');
   }else{

    alert("Data missing!!!");
 }
}

 })

     } catch (errors) {
    alert(errors);
} 
}    SignupHandler=()=>{
        this.props.navigation.navigate('DrewerNav')
    }
    SignuptologinHandler=()=>{
        this.props.navigation.navigate('SigntoLogin')
    }
  render() {
    const { photo } = this.state;
    return (

      <KeyboardAvoidingView
      style={styles.wrapper}
      >

        <View style={styles.scrollWrapper}>
 <ScrollView style={styles.scrollView}>
 <View style={styles.LogoContainer}>
 <Image source={require('../Images/avatar1.png')} style={styles.Logo}  onPress={this.handleChoosePhoto} />

 <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>

        {photo && (
          <Image
            source={{ uri: photo.uri,
              type: "image/jpeg",
              name: photo.filename  }}
            style={{ width: 125, height: 125,borderRadius:80}}

          />

        )
        }
      <TouchableOpacity >
        <Icon  name="image" size={30} color="#222" marginTop='30' position='absolute' onPress={this.handleChoosePhoto}position='relative'/>
          </TouchableOpacity>
      </View> 
        <Text style={styles.createNew1}>  CREATE ACCOUNT</Text>  
        </View>
        <View>

        <Form style={styles.inputwrapper} >

            <Item  >
            <Icon  name="user" size={25} color="white"/>
              <Input     style={styles.input}
                          placeholder='Your name'
                          placeholderTextColor={'white'}
                         name="name"
                         onChangeText={text => this.setState({ name: text })}
              />
            </Item>
            <Item >
            <Icon  name="mail-bulk" size={25} color="white"/>
              <Input style={styles.input}
                      placeholder='Your e-mail'
                      placeholderTextColor={'white'}
                    name="email"
                    onChangeText={text => this.setState({ email: text })}
               />
            </Item>
            <Item   >
            <Icon  name="lock" size={25} color="white"/>
              <Input  style={styles.input}
                      secureTextEntry 
                      placeholder='Your password'
                      placeholderTextColor={'white'}
                      name="password"
                      onChangeText={text => this.setState({ password: text })}
              />
            </Item >
            <Item  >
            <Icon  name="unlock" size={25} color="white"/>
              <Input  style={styles.input}
                      secureTextEntry 
                      placeholder='Confirm password'
                      placeholderTextColor={'white'}
                      name="password"
              />
            </Item>
          </Form>
        </View>
        <View>
          <TouchableOpacity >
          <Button style={styles.btnLogin} onPress={this.onPressSubmitButton.bind(this)}

    >
            <Text style={styles.text} >Sign Up </Text>
            </Button>
          </TouchableOpacity>
          <TouchableOpacity onPress={this.SignuptologinHandler}  >
          <Text style={styles.createNew}>  Have an account ?LOG IN</Text>  
          </TouchableOpacity>
      </View>
      </ScrollView>
 </View>
      </KeyboardAvoidingView>
    );
  }
}

1 Ответ

0 голосов
/ 27 июня 2019
createFormData = () => {

    console.log("RESPOSTA FORMDATA")
    console.log("NAME: " + this.state.photo.fileName);
    console.log("TYPE: " + this.state.photo.type);
    console.log("URI: " + this.state.photo.uri);
    console.log("PATH: " + this.state.photo.path);

    var foto = {
      uri: Platform.OS === "android" ? this.state.photo.uri : this.state.photo.uri.replace("file://", ""),
      type: this.state.photo.type,
      name: this.state.photo.fileName,
      path: this.state.photo.path
    };


    const fotoUsuario = new FormData();

    fotoUsuario.append("foto", foto)

    return fotoUsuario;

  };
...