Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android axios doesnot upload images using expo react native #33787

Closed
shaoor1994 opened this issue May 9, 2022 · 9 comments
Closed

Android axios doesnot upload images using expo react native #33787

shaoor1994 opened this issue May 9, 2022 · 9 comments
Labels
Component: Image Platform: Android Android applications. Platform: iOS iOS applications. Resolution: For Stack Overflow A question for Stack Overflow. Applying this label will cause issue to be closed.

Comments

@shaoor1994
Copy link

shaoor1994 commented May 9, 2022

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(R) Core(TM) 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>
 
);

}
}

`

@princefishthrower
Copy link

@shaoor1994 - what versions of axios are you using?

There was a recent regression in form data specifically in React Native environments: axios/axios#4412

@shaoor1994
Copy link
Author

@princefishthrower I am using
axios= "0.26.1",

@princefishthrower
Copy link

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

@shaoor1994
Copy link
Author

@princefishthrower ok Thanks for the response I will check and post here if its works or not

@shaoor1994
Copy link
Author

@princefishthrower It didnot solved my issue.My issue is still same with same error

@cortinico
Copy link
Contributor

As mentioned by @princefishthrower, this is not a React Native issue.
Please open an issue against either:

  • github.com/expo/expo
  • github.com/axios/axios

@cortinico cortinico added Resolution: For Stack Overflow A question for Stack Overflow. Applying this label will cause issue to be closed. and removed Needs: Triage 🔍 labels May 9, 2022
@github-actions
Copy link

github-actions bot commented May 9, 2022

We are using GitHub issues exclusively to track bugs in the core React Native library. Please try asking over on Stack Overflow as it is better suited for this type of question.

@GeorgeFlorian
Copy link

This worked for me on EXPO SDK 49:
I've installed expo-build-properties using npx expo install expo-build-properties and then added it as a plugin in app.json:

    "plugins": [
      [
        "expo-build-properties",
        {
          "android": {
            "usesCleartextTraffic": true
          }
        }
      ]
    ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Component: Image Platform: Android Android applications. Platform: iOS iOS applications. Resolution: For Stack Overflow A question for Stack Overflow. Applying this label will cause issue to be closed.
Projects
None yet
Development

No branches or pull requests

6 participants