
Android upload image to server using php mysql in this tutorial we are going to create a application which will Upload Image to Server. We will pickup image form gallery or form camera directly and will upload to hosting server. Our application will save image to specified folder on server and will save its path to Mysql server along with image name.So lets see how we can upload image to server using php mysql step by step.
Lets Start By Installing XAMPP Server
Before do anything firstly check you have XAMPP Server on your system or not. Alternatively you can use WAMP (For Windows), LAMP (For Linux) and MAMP (For MAC).
If you don’t have XAMPP Server you can Download and Install form https://www.apachefriends.org/download.html
Start Apache and Mysql form XAMPP Control Panel.
Creating Database and Table
Open phpmyadmin to open this type localhost/phpmyadmin in Internet Browser and Create a Database and Table.
Creating Database
1 |
CREATE DATABASE AndroidUploadImage; |
Creating Table
1 2 3 4 5 6 |
CREATE TABLE IF NOT EXISTS `imageupload` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `image_path` varchar(100) NOT NULL, `image_name` varchar(100) NOT NULL, PRIMARY KEY (`uid`) ); |
That’s it from Mysql Database part lets move to Php part.
Creating PHP Files
In this part we will create two files –
- config.php– This file will have Database Name, Username and Password.
- upload-image-to-server.php– This file receive image send form android application and store in server.
Open htdocs folder under C:\xampp and Create folder Android Upload Image .Under this folder create one upload folder. This upload folder will store all image send by android application.
Let’s create php files-
- config.php-
1 2 3 4 5 6 7 8 9 10 |
<?php //Define your host here. $servername = "localhost"; //Define your database username here. $username = "root"; //Define your database password here. $password = ""; //Define your database name here. $dbname = "androiduploadimage"; ?> |
- upload-image-to-server.php-
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 |
<?php include 'config.php'; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); if($_SERVER['REQUEST_METHOD'] == 'POST') { $DefaultId = 0; $ImageData = $_POST['image_data']; $ImageName = $_POST['image_tag']; $ImagePath = "upload/$ImageName.jpg"; $ServerURL = "yourPath/$ImagePath"; $InsertSQL = "INSERT INTO imageupload (image_path,image_name) values('$ServerURL','$ImageName')"; if(mysqli_query($conn, $InsertSQL)){ file_put_contents($ImagePath,base64_decode($ImageData)); echo "Your Image Has Been Uploaded."; } mysqli_close($conn); }else{ echo "Please Try Again"; } ?> |
We are done with php part now lets start java part.
Android Upload Image To Server Using Php MySql
Creating JAVA Files
- Create a new project in Android Studio File–>New–>New Project.
- Enter Application Name, Package Name, Select Empty Activity and click on finish.
- Our application will use Internet to send image to server and we will also need to use Camera access permission to use camera and permission to write into external storage to so firstly we need to add all these permission in AndroidManifest.xml file. Open your AndroidManifest.xml file and add following permission.
1 2 3 |
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> |
- Now lets design our interface. We need one imageview which will show image which we will select from Gallery or Camera, one edittext box to get image name and two button one for selecting image and another for sending image to server.Open activity_main.xml file and write below code.
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 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="10dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:paddingTop="10dp" android:background="#E0E0E0" android:focusable="true" android:focusableInTouchMode="true"> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/linearLayout"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Upload Image To Server" android:textSize="26dp" android:textColor="#000" android:fontFamily="sans-serif" android:paddingBottom="4dp"/> <RelativeLayout android:layout_width="fill_parent" android:layout_height="1dp" android:background="#000" android:layout_marginBottom="10dp"> </RelativeLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Image Name" android:layout_marginTop="10dp"/> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/imageName"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Select Image" android:id="@+id/buttonSelect" android:background="#FFF" android:layout_margin="10dp"/> <ImageView android:layout_width="fill_parent" android:layout_height="270dp" android:id="@+id/imageView"/> <RelativeLayout android:layout_width="fill_parent" android:layout_height="1dp" android:background="#000" android:layout_marginBottom="10dp" android:layout_marginTop="10dp"> </RelativeLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="right"> <Button android:layout_width="200dp" android:layout_height="wrap_content" android:text="Upload >>" android:textColor="#FFF" android:background="@color/colorPrimary" android:id="@+id/buttonUpload" android:visibility="gone"/> </LinearLayout> </LinearLayout> </ScrollView> </RelativeLayout> |
- Now the main part open your MainActivity.java file. We will declare all edittext, button and required variables.By taping on Select Image button we need to chose between either we want image form gallery or from camera.After selecting image we can now send it image to server by using upload button.Complete code for MainActivity.java 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
package com.androidcodefinder.androiduploadimage; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; public class MainActivity extends AppCompatActivity { Button GetImageFromGalleryButton, UploadImageOnServerButton; ImageView ShowSelectedImage; EditText imageName; Bitmap FixBitmap; String ImageTag = "image_tag" ; String ImageName = "image_data" ; ProgressDialog progressDialog ; ByteArrayOutputStream byteArrayOutputStream ; byte[] byteArray ; String ConvertImage ; String GetImageNameFromEditText; HttpURLConnection httpURLConnection ; URL url; OutputStream outputStream; BufferedWriter bufferedWriter ; int RC ; BufferedReader bufferedReader ; StringBuilder stringBuilder; boolean check = true; private int GALLERY = 1, CAMERA = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GetImageFromGalleryButton = (Button)findViewById(R.id.buttonSelect); UploadImageOnServerButton = (Button)findViewById(R.id.buttonUpload); ShowSelectedImage = (ImageView)findViewById(R.id.imageView); imageName=(EditText)findViewById(R.id.imageName); byteArrayOutputStream = new ByteArrayOutputStream(); GetImageFromGalleryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showPictureDialog(); } }); UploadImageOnServerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GetImageNameFromEditText = imageName.getText().toString(); UploadImageToServer(); } }); if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{android.Manifest.permission.CAMERA}, 5); } } } private void showPictureDialog(){ AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this); pictureDialog.setTitle("Select Action"); String[] pictureDialogItems = { "Photo Gallery", "Camera" }; pictureDialog.setItems(pictureDialogItems, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: choosePhotoFromGallary(); break; case 1: takePhotoFromCamera(); break; } } }); pictureDialog.show(); } public void choosePhotoFromGallary() { Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent, GALLERY); } private void takePhotoFromCamera() { Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, CAMERA); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == this.RESULT_CANCELED) { return; } if (requestCode == GALLERY) { if (data != null) { Uri contentURI = data.getData(); try { FixBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI); // String path = saveImage(bitmap); //Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show(); ShowSelectedImage.setImageBitmap(FixBitmap); UploadImageOnServerButton.setVisibility(View.VISIBLE); } catch (IOException e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show(); } } } else if (requestCode == CAMERA) { FixBitmap = (Bitmap) data.getExtras().get("data"); ShowSelectedImage.setImageBitmap(FixBitmap); UploadImageOnServerButton.setVisibility(View.VISIBLE); // saveImage(thumbnail); //Toast.makeText(ShadiRegistrationPart5.this, "Image Saved!", Toast.LENGTH_SHORT).show(); } } public void UploadImageToServer(){ FixBitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream); byteArray = byteArrayOutputStream.toByteArray(); ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT); class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> { @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = ProgressDialog.show(MainActivity.this,"Image is Uploading","Please Wait",false,false); } @Override protected void onPostExecute(String string1) { super.onPostExecute(string1); progressDialog.dismiss(); Toast.makeText(MainActivity.this,string1,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(Void... params) { ImageProcessClass imageProcessClass = new ImageProcessClass(); HashMap<String,String> HashMapParams = new HashMap<String,String>(); HashMapParams.put(ImageTag, GetImageNameFromEditText); HashMapParams.put(ImageName, ConvertImage); String FinalData = imageProcessClass.ImageHttpRequest("http://192.168.1.5/Android%20Upload%20Image/upload-image-to-server.php", HashMapParams); return FinalData; } } AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass(); AsyncTaskUploadClassOBJ.execute(); } public class ImageProcessClass{ public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) { StringBuilder stringBuilder = new StringBuilder(); try { url = new URL(requestURL); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setReadTimeout(20000); httpURLConnection.setConnectTimeout(20000); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); outputStream = httpURLConnection.getOutputStream(); bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(bufferedWriterDataFN(PData)); bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); RC = httpURLConnection.getResponseCode(); if (RC == HttpsURLConnection.HTTP_OK) { bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); stringBuilder = new StringBuilder(); String RC2; while ((RC2 = bufferedReader.readLine()) != null){ stringBuilder.append(RC2); } } } catch (Exception e) { e.printStackTrace(); } return stringBuilder.toString(); } private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException { stringBuilder = new StringBuilder(); for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) { if (check) check = false; else stringBuilder.append("&"); stringBuilder.append(URLEncoder.encode(KEY.getKey(), "UTF-8")); stringBuilder.append("="); stringBuilder.append(URLEncoder.encode(KEY.getValue(), "UTF-8")); } return stringBuilder.toString(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 5) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Now user should be able to use camera } else { Toast.makeText(MainActivity.this, "Unable to use Camera..Please Allow us to use Camera", Toast.LENGTH_LONG).show(); } } } } |
Now Run your project . So that’s all for this Android Upload Image to Server Using Php MySql. If you will get any error or confusion regarding this Android Upload Image to Server Using Php MySql you can comment below.
Screen Shot
Download Source Code
Subscribe To Our YouTube Channel
Like Us On Facebook
How to make resolution of photos maked by camera more? Thank u very much!
Could you solve it?
Solved
i have run project but my image is not uploading. i got blank toast message.
i am confused. help me.
Make sure you are writing correct url. In my project it is “http://192.168.1.5/Android%20Upload%20Image/upload-image-to-server.php”.
Check Yours..
how to have that file path kindly guide meee
it shows undefined image_data and path nd what is your parth in upload-image-to-server.php…
Hello,
Go to your cmd and type ipconfig and press enter. Use ipv4 address followed by file path.
e.g. – http://your ipv4 adress/your file path
Dear Sumeet ,
Why is the resolution smaller after uploading the photo ?
Is there any way to keep original resolution ?
Thanks !
Hello..
Change this to 100 for full resolution..
//FixBitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
Dear Sumeet ,
Why is the resolution smaller after uploading the photo ?
Is there any way to keep original resolution ?
Thanks !
Hello..
Change this to 100 for full resolution..
//FixBitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
The image remains in memory
how to clear the memory?
hello .i have question. you have tutorial read image for server using php mysql ?
I will Post Tutorial in this topic and let you know..
Like my Facebook Page for more updates…
Thanks..
image is uploading but showing 0byte and 0.jpg
same here. Did you found the solution?
hey how do you solve this problem ?
The script works perfectly thanks. However i would like to upload multiple images. Could you please assist. Thanks
hi i want to add image with name family mobile and adress
how i can add this data
exampel student with name last name age mobile and his image
tnx bro
same here. Did you found the solution?
How i can resize for normally size from camera
What’s up to all, because I am truly eager of reading this weblog’s post to be
updated daily. It includes good stuff.
Hello,
Thank foe this tuto.
But, i have problem : image is uploading but showing 0byte
Can you help me
Please
Hello,
Thank for tuto.
But i have problem : image is uploading but showing 0byte
Help me
Please
it show “undefined index ‘image_data’ and ‘image_tag’ it problem from POST method waht ishould do?
it show the message “Undefined index in’image_data’ and ‘image_tag'” in POST method what i should to fix it
same here, do you solved the problem ?
Thanks. But If I upload an image from the camera, the resolution is much lower and I have set the quality with 100. Contrary to the gallery that does not lower quality.
Solved!
at this line i m getting error //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
The error is : java.lang.NullPointerException
at android.graphics.Bitmap.compress
Hello!
When i run the project image uploading not works,
Show a empty Toas please hellp me,
I think the is corect.
I couldn’t refrain from commenting. Perfectly written!
how to add two edittext in android and therefore to get to the database?
Excellent beat ! I wish to apprentice while you amend your
web site, how could i subscribe for a blog web site?
The account helped me a acceptable deal. I had been a
little bit acquainted of this your broadcast offered bright
clear idea
where is target folder uploading?
Under your root directory create a folder name “upload” . It will store images.
I am trying to upload the images to mysql server using android studio the images are being uploaded to the database but when i display or try to re-upload the images are being repeated the select button is not taking the new image it is uploading the previous image itself which i have uploaded. I am unable to find the solution please guide me to do so as i am fresher.plz anwser me
Email your project to csesumeet@gmail.com
Hi i have mailed you the details please check and leave me a reply…waiting for your reply
Thank you..
Good afternoon,
I completed the upload image project. It worked perfect on the android emulator.
By performing the test on the mobile device, no result is achieved.
The device is on the same Wi-Fi network.
For testing I typed the ip of the server into the browser and showed the message:
Can not access this site
Can not access:
http://192.168.1.25/Android_Upload_Image/upload-image-to-server.php
ERR_ADDRESS_UNREACHABLE
————————-
Someone to help me solve this error. I’ll be very thankfull.
open cmd and type ipconfig check ipv4 address you are using the right ip or not.
I am uploaded my project in ur email….plz answer me and solve my problem..
Hi, what a great tutorial. But I get the message Undefined index: image_data from the php, and at the server, creates an empty file with the name given.
Someone to help me solve this error. I’ll be very thankfull.
while uploading image taken from camera.. The size resolution getting too small…Give me the solution for this problem???
Saved as a favorite, I like your website!
I used to be able to find good advice from your articles.
I am trying to upload the images to localhost using android studio the images are being uploaded to the database but when try to re-upload, the images are being repeated.it is not taking the new image, it is uploading the previous image itself which i have uploaded. I am unable to find the solution please guide me.
how to add 2 edit text again to the database ? Please help me ,,,
how to add two more edit text to the database, help me
You are a really persuasive writer. I can see this in your writeup. You’ve a way of writing compelling info that sparks significantly interest. gdedcdgbeedd
I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to know where u got this from. thank you kebbgfaeagcd
Email me at csesumeet@gmail.com
Hello, I completed the upload image project. It worked perfect on the android emulator.
But if I use 4G net, it not work. How to solve?
Hello!
i changed 40 to 100 but image quality good
please help me
$ServerURL = “yourPath/$ImagePath”;
I do not understand the meaning of yourpath. can you explain?
means url of image from that you can retrieve your image.
what is Your path in server url section of the php file
It could be path or address of your localhost or server or website.