Image uploading is one of the most usable functionality in react native development area because in today scenario every android and iOS application is fully dynamic and comes with Login functionality where user can set his own image as profile picture or upload images from his application. So in this tutorial we would going to create a react native application to Upload Image to Server using PHP MySQL and Store Image URL in Database so it can be accessible for further use from directly server.
What we are doing in this project : We would store the image into a folder created in our hosting server root directory and after successfully done the uploading process we would store the complete image URL(Path of Server) into MySQL database using PHP scripting language after that we would show a response message to user in react native application.
List of React Native libraries used in this project :
- react-native-image-picker : To pick image form gallery or camera.
- rn-fetch-blob : Send selected image to server.
Contents in this project React Native Upload Image to Server using PHP MySQL-Store Image URL in Database iOS Android Example Tutorial:
1. Installing the react-native-image-picker library :
1. Before getting started we need to install the react-native-image-picker library in our current project. To install the react-native-image-picker library you need to open your react native project folder in Command Prompt or Terminal and execute below command .
1 |
npm install react-native-image-picker@latest --save |
3. After installing the library we need to execute the
react-native link command , This command will refresh and re-index the complete react native project folder and index the react native image picker library in your current project.
4. Configure Project for Android devices :
1. Open build.gradle file present in your folder located in YourReactNativeProject/android.
2. Replace classpath ‘com.android.tools.build:gradle:2.2.+’ on previous line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.+' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } } |
3. Now open YourReactNativeProjectFolder/android/gradle/wrapper/gradle-wrapper.properties file and replace previous distributionUrl line to this distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip .Below is the complete source code of gradle-wrapper.properties file.
1 2 3 4 5 |
distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip |
4. Finally Open AndroidManifest.xml file present inside YourReactNativeProjectFolder\android\app\src\main and Add CAMERA permission and WRITE_EXTERNAL_STORAGE permission. Below is the final code of AndroidManifest.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.imagepickerproject" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="22" /> <application android:name=".MainApplication" android:allowBackup="true" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> </application> </manifest> |
5. Configure Project for iOS devices :
1. Open YourReactNativeProject -> ios – > YourProjectName.xcodeproj file.
2. Now we need to open info.plist file from side panel, This file contain all the useful information about your project.
3. Click on the Small + Plus icon present on the top.
4. Select the Privacy – Camera Usages Description permission like i did in below screenshot.
5. Select Privacy – Photo Library Usages permission .
6. Now we need to enter some info text in front of both permissions like i did in below screenshot so we remember what is the purpose of this permission.
2. Installing the rn-fetch-blob library :
1. Open your react native project folder in CMD and execute below command like i did in below screenshot.
1 |
npm install --save rn-fetch-blob |
2. After successfully install the library we need to execute
react-native link command in order to refresh our complete project and index the react native fetch blob library.
3. Creating MySQL database+Table on your PhpMyAdmin Server :
1. Create a new database in your PHPMYADMIN control panel named as mydatabase .
2. Inside this database we need to make a table named as image_upload_table with 3 columns id, image_tag and image_path. See the below MySQL table screenshot to know how to set their values. This table is used to store the complete image URL with domain name and a image tag.
4. Creating PHP Script to receive and store send image on Server and Insert image URL in MySQL database:
I have created a folder name as Project and inside the folder i have created another folder name as Uploads . So all the images will upload inside the Uploads folder.
Code for upload_image.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?php //Define your host here. $hostname = "localhost"; //Define your database User Name here. $username = "root"; //Define your database Password here. $password = ""; //Define your Database Name here. $dbname = "mydatabase"; $conn = mysql_connect($hostname, $username, $password); mysql_select_db($dbname, $conn); // Type your website name or domain name here. $domain_name = "http://192.168.2.102/Project/" ; // Image uploading folder. $target_dir = "uploads"; // Generating random image name each time so image name will not be same . $target_dir = $target_dir . "/" .rand() . "_" . time() . ".jpeg"; // Receiving image tag sent from application. $img_tag = $_POST["image_tag"]; // Receiving image sent from Application if(move_uploaded_file($_FILES['image']['tmp_name'], $target_dir)){ // Adding domain name with image random name. $target_dir = $domain_name . $target_dir ; // Inserting data into MySQL database. mysql_query("insert into image_upload_table ( image_tag, image_path) VALUES('$img_tag' , '$target_dir')"); $MESSAGE = "Image Uploaded Successfully." ; // Printing response message on screen after successfully inserting the image . echo json_encode($MESSAGE); } ?> |
5. Start Coding of React Native :
1. Open your project’s App.js file.
2. Import StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, TextInput and Alert component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, TextInput, Alert } from 'react-native'; |
3. Import ImagePicker and RNFetchBlob module from react-native-image-picker and rn-fetch-blob library .
1 2 3 |
import ImagePicker from 'react-native-image-picker'; import RNFetchBlob from 'rn-fetch-blob'; |
4. Create a class named as Project in your App.js file.
1 2 3 4 5 6 |
export default class Project extends Component { } |
5. Create constructor() in your project folder with 3 States named as ImageSource, data and Image_TAG.
ImageSource : Used to hold the image path when we select image from gallery or capture image form camera.
data : Used to hold the selected image as object to send on sever.
Image_TAG : Used to hold the image tag, some text send with image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
constructor() { super(); this.state = { ImageSource: null, data: null, Image_TAG: '' } } |
6. Create two functions named as selectPhotoTapped and ImagePicker.showImagePicker , these both functions is predefined inbuilt functions of react native image picker library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; this.setState({ ImageSource: source, data: response.data }); } }); } |
7. Create another function named as uploadImageToServer(). Inside this function we would simply use the RNFetchBlob.fetch() method to upload the selected image on our server. We are testing this application on our localhost so i am putting my IP address here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
uploadImageToServer = () => { RNFetchBlob.fetch('POST', 'http://192.168.2.102/Project/upload_image.php', { Authorization: "Bearer access-token", otherHeader: "foo", 'Content-Type': 'multipart/form-data', }, [ { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data }, { name: 'image_tag', data: this.state.Image_TAG } ]).then((resp) => { var tempMSG = resp.data; tempMSG = tempMSG.replace(/^"|"$/g, ''); Alert.alert(tempMSG); }).catch((err) => { // ... }) } |
8. Create 2 Touchable opacity component and 1 Text Input component inside render’s return block .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
render() { return ( <View style={styles.container}> <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> <View style={styles.ImageContainer}> {this.state.ImageSource === null ? <Text>Select a Photo</Text> : <Image style={styles.ImageContainer} source={this.state.ImageSource} /> } </View> </TouchableOpacity> <TextInput placeholder="Enter Image Name " onChangeText={data => this.setState({ Image_TAG: data })} underlineColorAndroid='transparent' style={styles.TextInputStyle} /> <TouchableOpacity onPress={this.uploadImageToServer} activeOpacity={0.6} style={styles.button} > <Text style={styles.TextStyle}> UPLOAD IMAGE TO SERVER </Text> </TouchableOpacity> </View> ); } |
9. Creating Style.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#FFF8E1', paddingTop: 20 }, ImageContainer: { borderRadius: 10, width: 250, height: 250, borderColor: '#9B9B9B', borderWidth: 1 / PixelRatio.get(), justifyContent: 'center', alignItems: 'center', backgroundColor: '#CDDC39', }, TextInputStyle: { textAlign: 'center', height: 40, width: '80%', borderRadius: 10, borderWidth: 1, borderColor: '#028b53', marginTop: 20 }, button: { width: '80%', backgroundColor: '#00BCD4', borderRadius: 7, marginTop: 20 }, TextStyle: { color: '#fff', textAlign: 'center', padding: 10 } }); |
10. Complete source code for App.js File :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
import React, { Component } from 'react'; import { StyleSheet, Text, View, PixelRatio, TouchableOpacity, Image, TextInput, Alert } from 'react-native'; import ImagePicker from 'react-native-image-picker'; import RNFetchBlob from 'rn-fetch-blob'; export default class Project extends Component { constructor() { super(); this.state = { ImageSource: null, data: null, Image_TAG: '' } } selectPhotoTapped() { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, storageOptions: { skipBackup: true } }; ImagePicker.showImagePicker(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; this.setState({ ImageSource: source, data: response.data }); } }); } uploadImageToServer = () => { RNFetchBlob.fetch('POST', 'http://192.168.2.102/Project/upload_image.php', { Authorization: "Bearer access-token", otherHeader: "foo", 'Content-Type': 'multipart/form-data', }, [ { name: 'image', filename: 'image.png', type: 'image/png', data: this.state.data }, { name: 'image_tag', data: this.state.Image_TAG } ]).then((resp) => { var tempMSG = resp.data; tempMSG = tempMSG.replace(/^"|"$/g, ''); Alert.alert(tempMSG); }).catch((err) => { // ... }) } render() { return ( <View style={styles.container}> <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}> <View style={styles.ImageContainer}> {this.state.ImageSource === null ? <Text>Select a Photo</Text> : <Image style={styles.ImageContainer} source={this.state.ImageSource} /> } </View> </TouchableOpacity> <TextInput placeholder="Enter Image Name " onChangeText={data => this.setState({ Image_TAG: data })} underlineColorAndroid='transparent' style={styles.TextInputStyle} /> <TouchableOpacity onPress={this.uploadImageToServer} activeOpacity={0.6} style={styles.button} > <Text style={styles.TextStyle}> UPLOAD IMAGE TO SERVER </Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#FFF8E1', paddingTop: 20 }, ImageContainer: { borderRadius: 10, width: 250, height: 250, borderColor: '#9B9B9B', borderWidth: 1 / PixelRatio.get(), justifyContent: 'center', alignItems: 'center', backgroundColor: '#CDDC39', }, TextInputStyle: { textAlign: 'center', height: 40, width: '80%', borderRadius: 10, borderWidth: 1, borderColor: '#028b53', marginTop: 20 }, button: { width: '80%', backgroundColor: '#00BCD4', borderRadius: 7, marginTop: 20 }, TextStyle: { color: '#fff', textAlign: 'center', padding: 10 } }); |
Screenshots:
Hi Admin,
Thanks for uploading this Tutorial…..
I have followed all steps …
But Unfortunately getting Error while i click “Upload image to Server button”
Error:
Rather i should get “Image uploaded Succesffully” Message
im getting the above error message.
Pls Help how to fix it….
Usmaan check the database username and password you put correctly and also replace my IP with your IP or domain .
Hi Admin,
I rechecked everything more than Twice,……
Everything looks perfect….
im getting error while uploading to server…
br tag error….. as
Fatal Error uncaught….
Usmaan send your code on [email protected] .
Hi admin,
I have send my code to your email id…..
My email id is [email protected]
Kindly revert back asap..
Thanks in advance.
can u please rectify my code too (same issue)
sir i uploaded the image successfully , but i don’t know how to retrieve it 🙁
can u help please?
Salma after uploading images on server we would store the images URL in Database, So simply create another php script to convert all the images data into JSon and then parse it in your application.
PLS HELP ME, I HAVE A ERROR
check my email.
ok Andres .
PLEASE HELP ME SIR !
Getting this error:
move_uploaded_file(user_images/106041686_1587990722.jpeg): failed to open stream: No such file or directory in C:\xampp\htdocs\UDAN\MyProject\PHP\upload.php on line 36↵↵Warning
Unable to move
i am working on your tutorial
React Native JSON FlatList with Images and Text iOS Android Tutorial
i saved the php files in my godaddy host(public html)
path: https://offnear.com/FlowerList.php while entering this path on browser i am getting the json out put . but i replaced https://reactnativecode.000webhostapp.com/FlowersList.php with my path .then app is not working.
kindly please help me .
Jithin i have checked your URL its showing a https error and after enabling it , it is showing the JSON . So solve the https error first .
the server side is ok right. in the react native side i didn’t make any modification rather than this: https://offnear.com/FlowerList.php .
i have no idea about https error
in json based php backend application( flowerslist)
can i use godaddyhosting accunt
Yes Jithin you can use Godaddy based hosting account .
thank you
Your welcome so your error solved ?
sorry it is still there. the server side is ok right. in the react native side i didn’t make any modification rather than this: https://offnear.com/FlowerList.php .
i have no idea about https error
Jithin send us your code on [email protected] .
i mailed the code( from [email protected])
now it is working .thank you for the grate support
Welcome Jithin 🙂 .
i go the same error as jithin
as Fatal Error uncaught….
How will I achieved this using expo, because am not seeing android folder in my project.
I am beginner.
Please help me out.
Thanks
Sahmwayne there is always a android named folder in react native project ? You are using Expo to test this code .
i am getting the following error pls help Thanks!
Cannot read property ‘showImagePicker’ of undefined
Raj try to install the image picker library again.
Hi Admin,
How to “Select and upload Multiple images” in one go, from Phone gallery….
Usmaan sorry but i haven’t tried that yet.
Hi admin,
Can we select multiple images and upload to server by pressing upload button…..by using “react-native-image-Picker”
Sorry bro i have not tried this yet.
Hi Admin,
Please suggest any library to select Multiple images….
https://github.com/ivpusic/react-native-image-crop-picker
rnfetchblob.documentdir undefined is not an object. sir i got this error , can u help me please?
Try to re-install the fetch blob library .
hi i am working with this same code but i am getting error in that please help me.
error is : Notice: Undefined index: image in C:\xampp\htdocs\FarmersPlaza\upload_image.php on line 23
code:
Manish if you run this file directly this would show error because currently there is value in this variable but when you call this file from React Native app then it will show no error.
How can we store the images directly to MySQL DB instead of storing it to the server and fetch it as a response and show it in our RN app?
Rohit you cannot store the image directly into MySQL db, you need to store the image URL in MySQL db and store image on your hosting server folder.
hi, admin. How to implement crop image inside here?
You need to use the crop image library to crop the image John.
Hi admin, Can I know how to upload multiple images using RNFetchBlob ?
Sorry ICE, currently i am learning about multiple image uploading.
Hi admin, Can I know how to upload multiple images using RNFetchBlob ?
Thanks admin, I have one question how can I make sure that images still maintain when I go to next page and return back this page no need to upload the same image again.
Silven you want to upload the different image each time or want to upload the same image ?
sir, can you give me your email, I need to ask you some question.
my email is : [email protected], after send the email please notifying using comment.
I already email sir.
sir, I want to maintain the same image.
Hi admin, I trying and error:
Notice: Undefined index: image_tag in /opt/lampp/htdocs/Project/upload_image.php on line 18
error here: $img_tag = $_POST[“image_tag”];
please tell me how to fix it? thanks
Here the image tag name should be same as the image tag name passed in react native code.
Hello, I send an email.
Warning: move_uploaded_file(uploads/1447882052_1556017341.jpeg): failed to open stream: No such file or directory in C:\xampp\htdocs\api\productdetail.php on line 26
this error comes when i hit the UPLOAD IMAGE TO SERVER button
Abubakar you need to create the uploads folder in your local hosting directory .
move_uploaded_file() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\api\productdetail.php on line 29
actually i guess your php code has no mechanism to receive image and image_tag variable
hello bro .
please verify your php backend code .
its not working properly
Abubakar its working properly i have just run it again right now, It is receiving the images properly from application. Could you tell on which platform you are testing the app like local or online ?
Hello, can’t we use distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip for the image upload?
Yes we can use but its good to use the latest gradle version.
Hello Admin, I sent you a mail.
mail received .
how to get the name of the image.
I don’t want to write a name in that box,
[simply get the original name of the image]
Thanks for asking this Akash, I have to look into it because i have done it by changing the name always .
Hi bro,my app doesnot working after i installed npm install react-native-image-picker —save this package.
Application Crash, When I use rn-fetch-blob
Please help me.
Did you link the library ?
// Receiving image sent from Application
if(move_uploaded_file($_FILES[‘image’][‘tmp_name’], $target_dir))
{
// Adding domain name with image random name.
$target_dir = $domain_name . $target_dir ;
}
Hi,This function doesn’t work bro..Help me.
hi how can i upload document insted of image?
uploaded image stored in local storage , but it doesnt show up in db
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /storage/ssd3/137/11242137/public_html/blog/addfeed.php:15 Stack trace: #0 {main} thrown in /storage/ssd3/137/11242137/public_html/blog/addfeed.php on line 15
I have also sent you an email. Please check your email.
Hello I’m having error in which i’m clicking the button but not getting the alert message and data is also not getting submitted.
try mysqli_* instead of mysql_connection because in php 7 or above it doesn’t support mysql_connection.
hello Admin,
I’m having the same error
Notice: Undefined index: image_tag in C:\xampp\htdocs\image_upload\image_upload.php on line 15
Notice: Undefined index: image_tag in C:\xampp\htdocs\image_upload\image_upload.php on line 16
Even I’m trying to insert the data it shows alert message and i’m getting error.
i need help
i am getting the information and image and I am unable to send that into the server folder
How can I upload images to server, which are placed within assets folder in project
three days have passed and I am trying without any result, I feel very disappointed, but when he found your code he worked great.
Really , you save my life , thanks you so mush .
Welcome bro 🙂 .
Hello Brother,
I am getting this error in upload_image.php. Please help me I am new here.
Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Project\upload_image.php on line 17
Notice: Undefined index: image_tag in C:\xampp\htdocs\Project\upload_image.php on line 29
Notice: Undefined index: image in C:\xampp\htdocs\Project\upload_image.php on line 32
Notice: Trying to access array offset on value of type null in C:\xampp\htdocs\Project\upload_image.php on line 32
Please help me sar.
Sir how to display this uploaded images using fetch
this is the error I’m getting…..” Cannot read property ‘DocumentDir’ of undefined” I don’t know if it’s because I’m using expo. please help out
Hi, I get this error, can someone please help… exactly following the codes
RNFetchBlob multipart request builder has found a field without
data
property, the fieldimage
will be removed implicitly.Ivan on which platform you are testing the app ? like locally or online ?
hi how do you upload multiple files at the same time
Takunda, I have not tried yet multiple files uploading at same time sorry .