React Native Image Upload as Form Data

北战南征 提交于 2020-01-25 07:27:06

问题


Postman formdata is working perfectly, but this returns following http 500 error. what is wrong with this block.


Response {type: "default", status: 500, ok: false, statusText: undefined, headers: Headers, …}headers: Headers {map: {…}}ok: falsestatus: 500statusText: undefinedtype: "default"url: "http://cupdes.com/api/v1/create-user"_bodyInit: ""_bodyText: ""proto: Object "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:


I may be very late in posting the answer but it may be helpful for others who encountered the same error. The following workflow worked for me. I used node.js as my backend.


const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true,
        path: 'images',
        cameraRoll: true,
        waitUntilSaved: true,
      },
    };


ImagePicker.showImagePicker(options, response => {
      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {

        let source = response;
        this.setState({profileImage: source});
      }
    });
  }

saveToServer(){
let {profileImage} = this.state;
// initilizing form data

let formData = new FormData();

formData.append('file', {
        uri: profileImage.uri,
        type: 'image/jpeg/jpg',
        name: profileImage.fileName,
        data: profileImage.data,
      });

    axios.post('http://192.156.0.22:3000/api/updateProfile', userDetail, {
      headers: {'Content-Type': 'multipart/form-data'},
    }).then(res => //)
      .catch(err => //);
}

And in the node server, I am doing something like this.

//index.js
//..
const formData = require('express-form-data');
//..
//
app.use(formData.parse());
// profile.js
profile.post('/updateProfile', async (req, res) => {
let imageCloud = await cloudinary.v2.uploader.upload(req.files.file.path, {
        use_filename: true
      });
}

Note: I'm using cloudinary to store my images. The above code is working for both android and iOS.

I hope this will help you in some extent.




回答2:


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;

  };


来源:https://stackoverflow.com/questions/56761078/react-native-image-upload-as-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!