question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Android axios doesnot upload images using expo react native

See original GitHub issue

Description

I am trying to upload image to a mongodb using expo react native using expo image picker but it returns with syntax error as it shows result in console but doesnot upload to server however it works fine with Post man

here is my form data:

const FormData = global.FormData; const formData = new FormData(); formData.append("name", this.state.name); formData.append("title", this.state.title); formData.append("contact", this.state.contact); formData.append("price", this.state.price); formData.append("description", this.state.description); formData.append("selectedcat", this.state.selectedcat); formData.append("selectedcity", this.state.selectedcity); formData.append("imgforsell",this.state.imgforsell)

here is my axios code :

axios .post( http://${ Platform.OS === “android” ? “192.168.88.45” : “localhost” }:4040/pets/addpets`, formData ) .then(({ data }) => { console.log(data); }) .catch((err) => { console.error(err.toJSON());

}) .finally(() => { this.setState({ name: “”, title: “”, contact: “”, price: “”, description: “”, selectedcat: “”, selectedcity: “”, imgforsell: “”, }); });

`

Version

“0.64.3”

Output of npx react-native info

System: OS: Windows 10 10.0.22000 CPU: (8) x64 11th Gen Intel® Core™ i7-1165G7 @ 2.80GHz Memory: 1.38 GB / 7.73 GB Binaries: Node: 16.14.2 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.18 - ~\AppData\Roaming\npm\yarn.CMD npm: 8.5.0 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: API Levels: 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 Build Tools: 28.0.3, 30.0.2, 32.0.0, 33.0.0, 33.0.0 System Images: android-24 | Google APIs Intel x86 Atom, android-24 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom Android NDK: Not Found Windows SDK: Not Found IDEs: Android Studio: Version 2020.3.0.0 AI-203.7717.56.2031.7935034 Visual Studio: Not Found Languages: Java: 17.0.1 - C:\Program Files\Common Files\Oracle\Java\javapath\javac.EXE npmPackages: @react-native-community/cli: Not Found react: 17.0.1 => 17.0.1 react-native: 0.64.3 => 0.64.3 react-native-windows: Not Found npmGlobalPackages:

Expo info

Expo CLI 5.2.0 environment info: System: OS: Windows 10 10.0.22000 Binaries: Node: 16.14.2 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.18 - ~\AppData\Roaming\npm\yarn.CMD npm: 8.5.0 - C:\Program Files\nodejs\npm.CMD SDKs: Android SDK: API Levels: 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 Build Tools: 28.0.3, 30.0.2, 32.0.0, 33.0.0, 33.0.0 System Images: android-24 | Google APIs Intel x86 Atom, android-24 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom IDEs: Android Studio: Version 2020.3.0.0 AI-203.7717.56.2031.7935034 npmPackages: expo: ^44.0.6 => 44.0.6 react: 17.0.1 => 17.0.1 react-dom: 17.0.1 => 17.0.1 react-native: 0.64.3 => 0.64.3 react-native-web: 0.17.1 => 0.17.1 react-navigation: ^4.4.4 => 4.4.4 Expo Workflow: managed

Steps to reproduce

I am trying to find fix Please let me know if any one has fix to this problem

Snack, code example, screenshot, or link to a repository

Complete frontend code

` import { View, Text, TextInput, Image, TouchableOpacity, StyleSheet, ScrollView, Picker, Platform, Alert, input, KeyboardAvoidingView //fetch } from “react-native”;

import mime from “mime”;

//const bodyParser = require(‘body-parser’) //router.use(bodyParser.json()); //router.use(bodyParser.urlencoded({ extended: true }));

import React, { Component } from “react”; import axios from “axios”;

import * as ImagePicker from ‘expo-image-picker’; import Constants from “expo-constants”; import * as FileSystem from ‘expo-file-system’; import QueryString from “qs”;

export default class Sellnow extends Component { constructor(props) { super(props); this.onChangePetName = this.onChangePetName.bind(this); this.onChangePetTitle = this.onChangePetTitle.bind(this); this.onChangePetContact = this.onChangePetContact.bind(this); this.onChangePetPrice = this.onChangePetPrice.bind(this); this.onChangePetDescription = this.onChangePetDescription.bind(this); this.onValueChangeCat= this.onValueChangeCat.bind(this); this.onValueChangeCity= this.onValueChangeCity.bind(this); this.onFileChange = this.onFileChange.bind(this); // this.pickImage = this.pickImage.bind(this); this.onSubmit = this.onSubmit.bind(this); // State this.state = { name: “”, title: “”, contact: “”, price: “”, description: “”, selectedcat:“”, selectedcity:“”, imgforsell:“”,

  //collection categories
  category: [
    
    {
      itemName: "Select Category...."
    },
    {
      itemName: "Pets Food"
    },
    {
      itemName: "Pets Products"
    },
    {
      itemName: "Pets Accessories"
    }
  ],

  // cities category
  cityCategory:[


    {
      itemName: "Select City...."
    },
    {
      itemName: "Islamabad"
    },
    {
      itemName: "Rawalpindi"
    },
    {
      itemName: "Lahore"
    },
    {
      itemName: "Peshawar"
    },
    {
      itemName: "Karachi"
    },
    {
      itemName: "Quetta"
    }

  ]
};

}

/componentDidMount() { axios.get(‘http://localhost:3000/PetsBazar/pets/’ ) .then(res => { this.setState({ name: res.data.name, title: res.data.title, contact: res.data.contact }); }) .catch((error) => { console.log(error); }) }/ onChangePetName(e) { this.setState({ name: e.target.value }); } onChangePetTitle(e) { this.setState({ title: e.target.value }); } onChangePetContact(e) { this.setState({ contact: e.target.value }); } onChangePetPrice(e) { this.setState({ price: e.target.value }); } onChangePetDescription(e) { this.setState({ description: e.target.value }); } // categories function onValueChangeCat(e) { this.setState({ selectedcat: e.targetvalue }) }

// city function onValueChangeCity(e) { this.setState({ selectedcity: e.targetvalue }) }

onFileChange(e) { this.setState({ imgforsell: e.targetvalue})}

// uploading Image

_getPhotoLibrary = async () => { let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, base64: true, exif: true, aspect: [4, 3] });

if (!result.cancelled) {
  this.setState({ imgforsell: result });
  
  
}
this.props.navigation.setParams({
  imgforsell: this.state.imgforsell
});

};

async onSubmit() { // e.preventDefault(); /*const petsObject = { name: this.state.name, title: this.state.title, contact: this.state.contact, price: this.state.price, description: this.state.description, selectedcat:this.state.selectedcat, selectedcity:this.state.selectedcity, imgforsell:this.state.imgforsell }; */

  //const formData = new FormData();
   const FormData = global.FormData;
  const formData = new FormData();
  formData.append("name", this.state.name);
  
  //formData.append("name",name);
  
  formData.append("title", this.state.title);

  //formData.append("title", title);
  
  formData.append("contact", this.state.contact);

  //formData.append("contact", contact);
 
  formData.append("price", this.state.price);

 // formData.append("price", price);
 
   formData.append("description", this.state.description);

  //formData.append("description", description);
 
  formData.append("selectedcat", this.state.selectedcat);

  //formData.append("selectedcat", selectedcat);
 
   formData.append("selectedcity", this.state.selectedcity);

 // formData.append("selectedcity", selectedcity);

 /* formData.append("imgforsell", {

    uri:imgforsell.uri,
    type:imgforsell.type

 });*/

formData.append("imgforsell",this.state.imgforsell)


  // from stack overflow

/*  const axiosInstance = axios.create({
    baseURL: '192.168.88.45:4000/PetsBazar/addpets', // use with scheme
    timeout: 30000,
    headers: {
        "X-Platform": 'android',
        "X-App-Build-Number": '1.0.0',
    },
});*/


  
 


  /*fetch(
    `"http://${
      Platform.OS === "android" ? " 192.168.88.45" : "localhost"
    }:4040/pets/addpets"`,
    formData,
    //'http://10.0.2.2:4040/pets/addpets/',
   //formData,
   
    {
      method: 'POST',
      //body: JSON.stringify(formData),
      // body:formData,
      mode: 'cors',
     headers: {
      //Accept: 'application/json',
     "content-Type": `multipart/form-data; boundary={formData._boundary}`,
  },
  body:QueryString.stringify(formData)
      
      
     // headers:{"Content-type":"application/json"}
    }
  )
    .then((res) => {
      if (!res.ok) {
        return Promise.reject(res);
      }
      return res.json();
    })
    .then((data) => {
      console.log(data);
    })
    .catch((err) => {
      console.error(err);
    })
    .finally(() => {
      this.setState({
        name: "",
        title: "",
        contact: "",
        price: "",
        description: "",
        selectedcat: "",
        selectedcity: "",
        imgforsell: "",
      });
    });

*/

axios .post( http://${ Platform.OS === "android" ? "192.168.88.45" : "localhost" }:4040/pets/addpets, formData ) .then(({ data }) => { console.log(data); }) .catch((err) => { console.error(err.toJSON());

}) .finally(() => { this.setState({ name: “”, title: “”, contact: “”, price: “”, description: “”, selectedcat: “”, selectedcity: “”, imgforsell: “”, }); }); }

render() {

const {imgforsell} = this.state



return (

  
  <View>
  <ScrollView
    nestedScrollEnabled={true}
    showsVerticalScrollIndicator={false}
  >
    <View style={styles.container}>
      <View style={styles.formContainer}>
        <Text style={styles.conText}>Please Fill the Below Form </Text>

        <View style={styles.borderForm}>
          <Text style={styles.formText}>Your Name</Text>
          <TextInput
            style={styles.formInput}
            multiline
            placeholder="Please Enter Your Name"
            maxLength={15}
            value={this.state.name}
            onChange={this.onChangePetName}
            blurOnSubmit={true}
            onChangeText={(name) => this.setState({ name })}
          />

          <Text style={styles.formText}>Category</Text>

         { /*<CategoryDropList />*/ }

         <View style={styles.viewStyle}>
        
         <Picker
      
       itemStyle={styles.itemStyle}
        mode="dropdown"
       style={styles.pickerStyle}
        selectedValue={this.state.selectedcat}
       // onValueChange={this.onValueChangeCat.bind(this)}
       //onValueChange={(selectedcat)=>this.setState({selectedcat})}
       onValueChange={(itemValue,itemIndex)=> this.setState({selectedcat:itemValue})}
    
      >
        {this.state.category.map((item, index) => (
          <Picker.Item
           
            color="black"
            label={item.itemName}
            value={item.itemName}
            index={index}
          />
        ))}
      </Picker>
     
      </View>

          

          <Text style={styles.formText}>Pet/Product Title</Text>
          <TextInput
            style={styles.formInput}
            placeholder="Enter Product Title"
            maxLength={15}
            value={this.state.title}
            blurOnSubmit={true}
            onChange={this.onChangePetTitle}
            onChangeText={(title) => this.setState({ title })}
          />

          <Text style={styles.formText}>City</Text>

          {/*<CityDropList />*/}

          <View style={styles.viewStyle}>

          <Picker
      
       itemStyle={styles.itemStyle}
        mode="dropdown"
       style={styles.pickerStyle}
        selectedValue={this.state.selectedcity}
       onValueChange={(itemValue,itemIndex)=> this.setState({selectedcity:itemValue})}
    
      >
        {this.state.cityCategory.map((item, index) => (
          <Picker.Item
           
            color="black"
            label={item.itemName}
            value={item.itemName}
            index={index}
          />
        ))}
      </Picker>

      

      </View>
          <Text style={styles.formText}> Contact Number </Text>
          <TextInput
            style={styles.formInput}
            placeholder="Phone Number"
            inputType="number"
            maxLength={11}
            keyboardType="number-pad"
            blurOnSubmit={true}
            value={this.state.contact}
            onChange={this.onChangePetContact}
            onChangeText={(contact) => this.setState({ contact })}
          />
          <Text style={styles.formText}>Price</Text>
          <TextInput
            style={styles.formInput}
            multiline
            placeholder="Enter Price"
            inputType="number"
            keyboardType="number-pad"
            blurOnSubmit={true}
            maxLength={7}
            value={this.state.price}
            onChange={this.onChangePetPrice}
            onChangeText={(price) => this.setState({ price })}
          />
          <Text style={styles.formText}>Image of Product</Text>

          {/*<ImagePickerExample />*/}

         

          <TouchableOpacity style={styles.btn} onPress={this._getPhotoLibrary.bind(this)}>
          <Text style={styles.btnTxt}> Choose File</Text> 
            </TouchableOpacity>
    
            {imgforsell ? (
          <Image source={{ uri: imgforsell.uri }} style={styles.uploadimgstyle} />
        ) : (
          <View/>
        )}
        
          
          <Text style={styles.formText}>
            Description(Optional max 150 words)
          </Text>
          <TextInput
            style={styles.descriptionInput}
            multiline
            placeholder="Describe your product"
            maxLength={150}
            blurOnSubmit={true}
            value={this.state.description}
            onChange={this.onChangePetDescription}
            onChangeText={(description) => this.setState({ description })}
          />
          <TouchableOpacity style={styles.btn} onPress={this.onSubmit}>
            <Text style={styles.btnTxt}>Submit</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  </ScrollView>
  </View>
 
);

} }

`

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
princefishthrowercommented, May 9, 2022

Yeah, that’s the problem. Upgrade to 0.27.2 or downgrade to 0.22.0. This is not a React Native issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

typescript - React Native - Axios- Expo Image picker
The images are not uploaded and I don't get the reason. I have tried everything but nothing seems to work. How I set...
Read more >
axios post image - Expo Snack
axios post image. No description. Open with Expo Go. Open in editor. Need Expo? Don't have the Expo Go? Download the app to...
Read more >
FormData not working after expo update to sdk 45. How do I ...
After expo sdk 45 the FormData does not work. Here is my code to upload profile pictures to my nodejs bakcend:
Read more >
Image Upload with React Native, Expo ImagePicker, Rails ...
Coding example for the question Image Upload with React Native, Expo ImagePicker, Rails, Axios and Paperclip-React Native.
Read more >
How to upload images from React Native to a Laravel API
Uploading images from a React Native app seems straightforward. However, React Native does not provide a direct way to connect the app with...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found