How to upload image in React Native

In this React Native source code example, the source code below illustrate how to upload image in React Native.

You can copy and adopt this source code example to your React Native project without reinventing the wheel.

import React, {Component} from 'react';
import {StyleSheet, Text, View, Image,ToastAndroid} from 'react-native';
/*Please follow the instructions on setting up react-native-image-crop-picker*/
import ImagePicker from 'react-native-image-crop-picker';
import Permissions from 'react-native-permissions';


export default class App extends Component {
  state = {
     photoPermission:'',
     cameraPermission:'',
     myImage:null
   }

  componentDidMount() {
    Permissions.request('storage').then(response => {
          this.setState({ photoPermission: response })
    })
    Permissions.request('camera').then(response => {
          this.setState({ cameraPermission: response })
    })
   }

  SelectImage(){
    ImagePicker.openPicker({
          width: 150,
          height: 150,
          cropping: true,
          includeBase64:true
        }).then(image => {
          console.log(image);
          this.setState({myImage:image})
        });
      }

    UploadImage(){
      var image= this.state.myImage;
      let base64Img = `data:${image.mime};base64,${image.data}`

      let apiUrl = 'https://api.cloudinary.com/v1_1/Your User Name/image/upload';

    let data = {
      "file": base64Img,
      "upload_preset": "Your Prese Key",
    }

    fetch(apiUrl, {
      body: JSON.stringify(data),
      headers: {
        'content-type': 'application/json'
      },
      method: 'POST',
    }).then(async response => {
        let data = await response.json()
        console.log(response)
        ToastAndroid.show('Image Succefully Uploaded', ToastAndroid.SHORT);
      }).catch(err=>console.log(err))
    }


  render() {
    return (
      <View style={styles.container}>
          <Text style={{padding: 20,backgroundColor:'#ddd', marginBottom: 10}}
          onPress={()=>this.SelectImage()}>Select Image</Text>

          <Text style={{padding: 20,backgroundColor:'#6ee7a5'}} onPress={()=>this.UploadImage()}>Upload Image</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.