React Native Image Upload作为表单数据 [英] React Native Image Upload as Form Data

查看:103
本文介绍了React Native Image Upload作为表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

邮递员formdata可以正常工作,但这在出现HTTP 500错误后返回.这个块有什么问题.

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: 未定义,标题:标题,…}标题:标题{map:{…}}好: falsestatus:500statusText:undefinedtype:"default" url: " http://cupdes.com/api/v1/create-user " _bodyInit : _主体: " proto :对象"rtghj"

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>
    );
  }
}

推荐答案

我发布答案可能很晚,但是对于遇到相同错误的其他人可能会有所帮助.以下工作流程为我工作.我将node.js用作后端.

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
      });
}

注意:我正在使用cloudinary存储图像. 上面的代码适用于android和iOS.

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.

这篇关于React Native Image Upload作为表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆