Hello friends, welcome to our new tutorial, in this android tutorial we will create a simple Android Upload Image to Server App using PHP and MySQL.
Android Upload Image using Android Upload Service
In this tutorial we will upload small image files from android to server. If need to upload larger files like a captured video check this tutorial
Android Upload Video to Server using PHP
If you want to see what exactly we will be creating in this Android Upload Image to Server app then you can see this video demonstration first.
Android Upload Image to Server Video Demonstration
If you liked the demonstration of Android Upload Image to Server App then go ahead to know how you can do this. Lets start creating our Android Upload Image to Server Project.
This Android Upload Image to Server is having two parts
- PHP MySQL
- Android Studio
Lets start with PHP MySQL for your Android Upload Image to Server app.
Android Upload Image to Server – PHP MySQL Part
- I am using hostinger hosting as my web server.
- So go to your hosting accounts PhpMyAdmin and create a new table.
- I have created the following table

- Now we need to create a php script for our database connection
- Create a new file named dbConnect.php and write the following code
1 2 3 4 5 6 7 8 9 | <?php define('HOST','mysql.hostinger.in'); define('USER','u502452270_andro'); define('PASS','belal_123'); define('DB','u502452270_andro'); $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); |
- Now we need one more php script to get and save our image sent from android device
- Create a new file upload.php and write the following 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 | <?php if($_SERVER['REQUEST_METHOD']=='POST'){ $image = $_POST['image']; require_once('dbConnect.php'); $sql = "INSERT INTO images (image) VALUES (?)"; $stmt = mysqli_prepare($con,$sql); mysqli_stmt_bind_param($stmt,"s",$image); mysqli_stmt_execute($stmt); $check = mysqli_stmt_affected_rows($stmt); if($check == 1){ echo "Image Uploaded Successfully"; }else{ echo "Error Uploading Image"; } mysqli_close($con); }else{ echo "Error"; } |
- Now upload both the files to your hosting account
- We need the address of upload.php file
- In my case the address of my upload.php is -> http://simplifiedcoding.16mb.com/ImageUpload/upload.php
Android Upload Image to Server – The Android Part
- Open android studio and create a new android project. (I have created ImageUploadSample)
- Firstly we will create a new class to handle our Http Request
- Right click on your package name and create a new java class (I created RequestHandler.java)
- Write the following 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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | package net.simplifiedcoding.imageuploadsample; import java.io.BufferedReader; import java.io.BufferedWriter; 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; /** * Created by Belal on 8/19/2015. */ public class RequestHandler { public String sendGetRequest(String uri) { try { URL url = new URL(uri); HttpURLConnection con = (HttpURLConnection) url.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String result; StringBuilder sb = new StringBuilder(); while((result = bufferedReader.readLine())!=null){ sb.append(result); } return sb.toString(); } catch (Exception e) { return null; } } public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) { URL url; String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); response = br.readLine(); } else { response = "Error Registering"; } } catch (Exception e) { e.printStackTrace(); } return response; } private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } } |
- In activity_main.xml we have to create the following layout

- For creating the above layout you can use the following xml 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 | <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/string_choose_file" android:id="@+id/buttonChoose" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/imageView" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/string_upload_image" android:id="@+id/buttonUpload" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/string_view_image" android:id="@+id/buttonViewImage" /> </LinearLayout> |
- Now come to MainActivity.java file
- First we will declare some variables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static final String UPLOAD_URL = "http://simplifiedcoding.16mb.com/ImageUpload/upload.php"; public static final String UPLOAD_KEY = "image"; public static final String TAG = "MY MESSAGE"; private int PICK_IMAGE_REQUEST = 1; private Button buttonChoose; private Button buttonUpload; private ImageView imageView; private Bitmap bitmap; private Uri filePath; |
- Inside onCreate method we will initialize our components
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); buttonView = (Button) findViewById(R.id.buttonViewImage); imageView = (ImageView) findViewById(R.id.imageView); buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); } |
- As you can see we have added setOnClickListener to the buttons.
- So now come to your onClick method and write the following code
1 2 3 4 5 6 7 8 9 10 11 | @Override public void onClick(View v) { if (v == buttonChoose) { showFileChooser(); } if(v == buttonUpload){ uploadImage(); } } |
- Here we have two methods showFileChooser() this method will show the gallery from where user can choose image to upload.
- When the user will choose an Image to upload, then after selection we will show that image to the ImageView we created in our main layout.
- These two methods will do all the require things
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } |
- Now we have the Image which is to bet uploaded in bitmap.
- We will convert this bitmap to base64 string
- So we will create a method to convert this bitmap to base64 string
1 2 3 4 5 6 7 8 9 | public String getStringImage(Bitmap bmp){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); return encodedImage; } |
- Now finally create uploadImage() method
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 | private void uploadImage(){ class UploadImage extends AsyncTask<Bitmap,Void,String>{ ProgressDialog loading; RequestHandler rh = new RequestHandler(); @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(Bitmap... params) { Bitmap bitmap = params[0]; String uploadImage = getStringImage(bitmap); HashMap<String,String> data = new HashMap<>(); data.put(UPLOAD_KEY, uploadImage); String result = rh.sendPostRequest(UPLOAD_URL,data); return result; } } |
- Now thats it for Android Image Upload to Server. You can see the final complete code below for MainActivity.java
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 | package net.simplifiedcoding.imageuploadsample; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final String UPLOAD_URL = "http://simplifiedcoding.16mb.com/ImageUpload/upload.php"; public static final String UPLOAD_KEY = "image"; public static final String TAG = "MY MESSAGE"; private int PICK_IMAGE_REQUEST = 1; private Button buttonChoose; private Button buttonUpload; private ImageView imageView; private Bitmap bitmap; private Uri filePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); buttonView = (Button) findViewById(R.id.buttonViewImage); imageView = (ImageView) findViewById(R.id.imageView); buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); } private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } public String getStringImage(Bitmap bmp){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); return encodedImage; } private void uploadImage(){ class UploadImage extends AsyncTask<Bitmap,Void,String>{ ProgressDialog loading; RequestHandler rh = new RequestHandler(); @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(MainActivity.this, "Uploading Image", "Please wait...",true,true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(Bitmap... params) { Bitmap bitmap = params[0]; String uploadImage = getStringImage(bitmap); HashMap<String,String> data = new HashMap<>(); data.put(UPLOAD_KEY, uploadImage); String result = rh.sendPostRequest(UPLOAD_URL,data); return result; } } UploadImage ui = new UploadImage(); ui.execute(bitmap); } @Override public void onClick(View v) { if (v == buttonChoose) { showFileChooser(); } if(v == buttonUpload){ uploadImage(); } } } |
So thats it for our Android Upload Image to Server app. In the next part of Android Upload Image to Server app we will see how we can fetch the uploaded images. You can also download the source code of this Android Upload Image to Server app from the link given below.
Android Upload Image to Server – Download Source Code
[wp_ad_camp_1]
Next Part – Download Image from Server using PHP MySQL.

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
First of all Thanks for posting this!
Can you help me with this I am getting “Error Registering ” as a toast when i try to Upload Images!
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
Where I am Wrong?
If you wrote the exact code as I have written then there is no possibilities of getting an Error Registering message.. This message is coming from your php script.. So I would suggest you to create an HTML page and try uploading image by sending request to the script.. and check if the upload is working or not..
Got it working today!
But it is not able to upload all Images!
Giving “Error Registering” for Images!
Waiting for your new Tutorial to get Images from Server!
Thanks Belal!
Not uploading all images means???
Pictures taken from phone cannot be used
belai my app is uploading but my getimage does not can i get the php file thanks
example not working please help i did exactly same as u show on page
check the manifest file, you need to put:
Error Registering is due to the dbConnect.php
I was also getting this error because i made dbconnect.php and in uploads.php i write it as dbConnect.php
So database connection was not making
Check this out
I have the same problem, files from phone does not upload
I download files from net then they get uploaded
Thanks Belal for the tutorial, l also have same error “error registering” and for public String sendGetRequest(String uri) for “sendGetRequest” is says not in use?
Actually this method sendGetRequest will be used when we fetch the uploaded image.. but in this part I did not cover fetching image.. So when I will publish the next part to fetch image from server we will use this method.. You can check by downloading my source code.. it is working correctly
I have an problem.that is net.simplifiedcoding.image process has stopped. please tell the answer for that
check logcat for the exact error
i want your original php script for upload and view image.please send me in reply
get the scripts from here
https://drive.google.com/file/d/0B0xicvl5x7QDWDJyX0FFZ0NTbXc/view?usp=sharing
Awesome. It’s working great. Is there any way I can upload tags or some other metadata to go in another column in the database? I saw a String MY_MESSAGE. Is that for another data field in a future tutorial? I’d like to be able to tag the pictures, dog, cat, girl, etc and then search the database by tag. Thanks again. I’m looking forward to your next tutorial.
Hello,
I try your tutorial and I have one problem, I’am getting “Error Registering ” . I must upload image wich I take my mobile phone. What I sholud do? I want take a picture and upload to server.
Can You help me?
Look forward to hearing from you. Thank you very much!
If your images are so large in size then you should not upload it to mysql database.. rather store the path of the image in mysql database in store image in a particular directory…
Try changing the datatype from blob to long blob it will support larger images
I changed to long blob and still I have the same problem. Ok, what I must change in php scrpit to save image in directory on my server?
Thank you very much!
I want tu upload picture and two string’s to mysql, what and where I can must change?
Can I counting on your help?
I’m looking forward to hearing from you.
you need to convert the base64 string to file.. and then you need to store it to a directory in your server.. I will try to post a new tutorial for this as well soon 🙂
How to upload video from android to server using php & mysql?
stay tuned and I will post tutorial of doing this also 🙂
Why does the app crash if in case, user along with image sends text to server and chooses at a instance to send only the text i.e. if no image is selected. How to make it optional to send image with text or only text?
stay tuned and I will post a tutorial for this as well
Belal,
That`s a great tutorial! Much better than the official one.
I have applied every single step and run the app on my phone (Samsung Galaxy s4). But I might be missing something since I have the following problem: 1 – GUI shows as expected, 2 – Click on choose image button, 3 – Select an image from the gallery, 4 – App stops running. The error message on the console is: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/27997 (has extras) }} to activity {com.example.h130145.imageuploadsample/com.example.h130145.imageuploadsample.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/27997 from pid=1319, uid=10061 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
Looks like there is some kind of permission issue but I could not figure out exactly where it is. Any idea what is going wrong? Thanks in advance!!!
try adding this line to your manifest
i wrote same code as mentioned but in android it’s showing toast and in php data is not saving? where is error?
rply asap
What toast message you are getting???
it’s showing br.
what are you using a live hosting or localhost using wamp/xampp server??
i am using xampp server … even i am getting toast message as
I am getting the same toast…I am using webhoat
Check the updated tutorial from here:
https://www.simplifiedcoding.net/android-upload-file-to-server/
hiii Belal,
I am following your code to upload image to server using php,mysql . but I’m getting ‘error uploading image’ message when i run upload.html file. all the php file are from your google drive.. what should I do? please help me!!
check if your database has something wrong??
hey.. i find out where i’m wrong.. but now when i try to open that image from wamp server..it download in BIN format.. what should i do to opn it in .jpeg…please help me!!!
We are uploading image to our MySQL database and it is in base64 string..
how to open blob image?? I tried with blob as well as longblob but the image download in .bin format
please guide me!!
Hi Bilal, this tutorial is very helpful for me But i have an issue with this can u plzzz help me??
Image uploading successfully While fetching the images some images are invisible because of its size and dimensions. Can u plz help me??
change database type blob to long blob if this is also not working then use this tutorial for really large image files
http://www.simplifiedcoding.net/android-upload-image-using-php-mysql-android-studio/
Thanks Belal,Its Working perfectly.
Hi, thanks for your great tutorial, I have hard time to insert both string and bitmap together into the mysql, can you please do a full tutorial on how to do it? I’m confused on the string params and my bitmap cant be use.
Okk I will post it tomorrow 🙂
here is your tutorial to upload text with image
http://www.simplifiedcoding.net/android-upload-image-from-gallery-with-text/
Thank You
Dear Belal Khan, thanks for your tutorial. I have facing some problem here. I created a same table with yours in my web hosting server and using your sample application to upload and retrieve the image. However, i found out that the picture i uploaded to database is not same with the original picture, some part is missing as white color presented in the picture. You can check it out at the following link (“http://tarucassist.comli.com/getImage.php?id=1 ).
The details of the picture is
width: 720
height: 1280
file size: 404kb
another example which is successfully display whole picture: http://tarucassist.comli.com/getImage.php?id=3
However, the size of this picture is smaller than the first 1 which details shows as below:
width: 250
height: 250
file size 42.0kb
may i ask it is the size problem or ?
Dear Belal Khan,
I realize I asked a duplicate question with Mushadiq and i appreciate for the solution. It work for me! thank you =D
Change the blob to long blob data type and it should work
Hi, I’ve changed to long blob but still have problem uploading large size image files to the MYSQL server. I search through the internet and found out that it may cause by the size of image file exceeded the max_allowed_packets by MYSQL server, any workaround? BTW I’m using webhost000 web server, thank you and appreciate your work.
try this tutorial – http://www.simplifiedcoding.net/android-upload-image-from-gallery-with-text/
where is getimage.php
In this tutorial I covered only the uploading part. to get the uploaded image check this tutorial – http://www.simplifiedcoding.net/android-download-image-from-server-using-php-and-mysql/
thanku for sharing ur tutorials are just awsm (y)
Thank You Keep visiting 🙂
hi
ihave problem with appcompatactivty not recognized please help.
br,
update your sdk.. or change AppCompatActivity to ActionbarActivity or only Activity
PHP Script Error Pls Help Me and also provide download facility of upload php file
Connect with me on facebook.com/probelalkhan I will try to help you using
Hi,
Great tutorial. I do have a question .
Why do you have to upload the image in bitmap and convert to base64 string.
Using basic html and php as the code below through the computer browser I can upload any image in its native format.
Can’t Android handle the raw picture file format such as *.png or *.jpg etc?
Standard upload code below:
Upload Data
File:
<?php
// connect to database
mysql_connect("localhost","myusername","mypassword") or die(mysql_error());
mysql_select_db("SharperApp_1") or die(mysql_error());
//file properties
$file = $_FILES['Image_1']['tmp_name'];
if (!isset($file))
echo "Please select an Image.";
else
{
$image = addslashes(file_get_contents($_FILES['Image_1']['tmp_name']));
$image_name = addslashes($_FILES['Image_1']['name']);
$image_size = getimagesize($_FILES['Image_1']['tmp_name']);
if ($image_size==FALSE)
echo "That's not an image.";
else
{
if (!$insert = mysql_query("INSERT INTO Inspection_Data VALUES ('','$image_name','','','','','','$image')"))
echo "Problem uploading image.";
else
{
$lastid = mysql_insert_id();
echo"Image Uploaded.Your image:”;
}
}
}
?>
No you can’t send image directly from android device to server… Though there is an option available for multipart http request I will try to post a tutorial for that as well
Thank You
thank you for this tutorial.
you have to add:
in android.manifest.
what to add??
The picture is not uploading to the database and i am getting toast as
What toast you are getting?
i also get toast .. why it happen ..? i using xamppp
Hello akmal,
Can i ask if you already got the answer for this? I have the same problem, I get toast something like that and i dont know why.. Hope you could help me. Thanks! 🙂
i get toast “/ br ” .. why ?
Check your emulator can access your host or not if you are using local server
i have the same problem it show what should i do ?
Did you guys solve that problem ?
Because i’m having the same right now
Please Help…
Can you please upload this tutorial using volley library.
Ok I will post a tutorial using volley library as well
You can check the new tutorial I just published to upload image using volley
http://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Hi ;
i don’t want to upload the image i just want to display it with text from mysql into my android app
Then you should check the tutorial about retrieving image from server
check it here -> http://www.simplifiedcoding.net/android-download-image-from-server-using-php-and-mysql/
Nice tutorial.
I’m trying to do this, but using restful services. In Android side I use Retrofit, in server side, I use slim.
I think this make everything a little easier. I’m just fighting with the php code. I receive the image, but I want to save it in a concret directory in server.
i cant upload a image it is showing one dot
Hi there, great tutorial !
When I try to select an image from the gallery, the app crashes.
Help please?
Dear Belal,
I have tried your code, both html and Android. Html is working fine, but Android give result 0 Byte in my SQL. Do you have any suggestion?
Dear sir, I have trouble in uploading image to server according to your source.when choose image, message ” Unfortunately, ImageUpload has stopped.
How to solve it. Please sir.
Sincerely.
Thura
check logcat for the error
I can see you upload the image by convert to bitmap and then to base64. If I want to upload files like .pdf, I’ll just have to skip the bitmap conversion, and make it to base64 before upload. is that true? some say “file is just a file anyway so it will work” so I want to confirm it from you.
I have same doubt. Belal help me on this
get_image ?
great work awesome thank you for this.
I would like to know how we can upload multiple images to the server at one shot.
Please help me with this.
Thanks alot !!!!!!
OMG this is what i am looking for 😀
this is the only tutorial that shows you how to do it on an actual server not wamp server
any chance you can add uploading a comment (text) with the string like a tag or so ??
it would be appreciated :))
god bless you
I have already posted a tutorial for this
check here http://www.simplifiedcoding.net/android-upload-image-from-gallery-with-text/
Hi belal,
can you please provide me a tutorial for getting all near by places? like restaurants,hospital in list view. just like food panda application. i will be very thankful to you.. 🙂
nice tutorial sir.. but i want to ask, hope you can help me… i i want to save strings and bitmap in one database.. what is the code ? since if bitmap you use “doInBackground(Bitmap… params)” and for string, “doInBackground(String…params)”, so how can i combine bitmap and string to save in database ? what is the code ? thank you sir 🙂
Check this tutorial
https://www.simplifiedcoding.net/android-upload-image-from-gallery-with-text/
Can i get code for retrieving all images stored in database from server in java
Hello Belal,
Can you get contact with me a freelencer project?
My mail is hakanogu@hotmail.com. Please write me.
Bro its been over a week and its really irritating im using 000webhost and i have tried a lot on this but all i am getting is PHP Error.
Use hostinger dont use 000webhost your use wamp server
lol its paid. in free version they are not accepting my account.
Contact me I will give you my hostinger account for testing.. contact on facebook.com/probelalkhan
Hi , Belal Khan
i used all your upload code but occur this error.i am using byethost.
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabe7fb00, error=EGL_SUCCESS
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab75d510
can u teach me how to solve this ?
A million thanks =)
Hi,
thank you for the helpful tutorial!!
I would really appritiate if you could help me-
each time I try to upload image I get the ‘Error Uploading Image’ error [from the php file],
how can I solve that???
thanks!!
thank god,
solved.
Hi Belal,
I am try to change url “http://192.168.1.41/ImageUpload/upload.php” for my local System. and Changed Php Script also. But Image not Uploaded and Shows empty Toast.
My Logcats Shows the Following Error,
java.net.ConnectException: failed to connect to /192.168.1.41 (port 80) after 15000ms: isConnected failed: EHOSTUNREACH (No route to host)
W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
W/System.err: at java.net.Socket.connect(Socket.java:882)
W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139)
W/System.err: at com.android.okhttp.Connection.connect(Connection.java:148)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:208)
W/System.err: at net.simplifiedcoding.imageuploadsample.RequestHandler.sendPostRequest(RequestHandler.java:59)
W/System.err: at net.simplifiedcoding.imageuploadsample.MainActivity$1UploadImage.doInBackground(MainActivity.java:118)
W/System.err: at net.simplifiedcoding.imageuploadsample.MainActivity$1UploadImage.doInBackground(MainActivity.java:92)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.ErrnoException: isConnected failed: EHOSTUNREACH (No route to host)
W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
Hi.,
Please Give me the Php Script. I’m using MySql db. I Cant acces Server. Logcat shows EHOSTUNREACH (No route to host) Error.
Please Help me.
Hi Belal,
I am using xampp as my server… how can i convert it?
thanks… hope you’ll help me for my capstone project.
Great Tutorial!!! My Problem is that the string response inside the toast generated from the uploadImage Async Task is empty and the image is never uploaded to my hostinger mysql database…. The image is taken from camera and it is about 1.5MB. Please Help….
You need to compress the image first.. create an scaled bitmap of new resolution and change the quality to 70 in toByteArray method
thanks !!! I will try this…
Thank you very much !
But this code is not running in eclips .
will this code not work in eclips .
I uploaded Image.. But how can i check whether the image was uploaded or not…
I have a login form where the user provide Name, mobile no. and Uploads image. I have implemented your example for uploading image but when i select the image i get an error that ” java.lang.RuntimeException: Unable to resume activity {com.example.moon.vendor/com.example.moon.vendor.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/55851 (has extras) }} to activity {com.example.moon.vendor/com.example.moon.vendor.MainActivity}: java.lang.NullPointerException”. What can be possible reason for this. please help.
sir i am facing one problem with php script my file gets uploaded but showing message unsucessful to upload and also it is not downloading files from server neither it is showing it with id=1 or id=2 as you have shown in the example,i done exactly same please help me
hey, i am working on this with postgresql database. but am getting error in android part.
Error:(141, 55) error: package net.simplifiedcoding.imageuploadsample does not exist
Error:(141, 118) error: package net.simplifiedcoding.imageuploadsample does not exist
Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
belal khan this tutorial very help full to me but
i can’t upload images with size more than 1 mb
can u help me
Thanks for this! I was just wondering if you have a tutorial on how to upload files i.e .pdf, .doc, .txt etc. TIA
me 2 I need to know how to upload fileds such as; .pdf, .doc into DB in server using android
for my project =)
process is displying “uploading image” but image is not uploading .
it doesn’t toast anything ..Toast is blank
even i ve same problem u found any soln
Same Problem with blank toast msg.. how to clear that pls tell
One more error occur in that is show a “Error Registering” … Clear me that error bro
I’m getting this error. Please Resolve this . 🙂
02-26 10:01:01.259 10396-11867/com.example.nitish.uploadimage E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.nitish.uploadimage, PID: 10396
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:602)
at com.example.nitish.uploadimage.MainActivity.getStringImage(MainActivity.java:79)
at com.example.nitish.uploadimage.MainActivity$1UploadImage.doInBackground(MainActivity.java:112)
at com.example.nitish.uploadimage.MainActivity$1UploadImage.doInBackground(MainActivity.java:89)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
can I do this tutorial for uploading file doc or pdf from my Android project and download it also or its just for images plz help T_T
process is displaying “uploading image” but image is not uploading .
it doesn’t toast anything ..Toast is blank
Can you please help me with it
He forgot to define the “$con” variable. That’s what is probably giving the problem. it’s the varibale that does the actual connection to the database.
I have another php class that has a function to connect:
conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
?>
then in the above php file I defined $con as follows:
// connecting to db
$db = new DB_Connect();
//sql connection
$con = $db ->connect();
sorry this is the other php file in full
conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
?>
process is displaying “uploading image” but image is not uploading .
it doesn’t toast anything ..Toast is blank
Please help me with this.
Hello avinash i am also facing the same problem can you help me if u have solved it.
Error Uploading Image
cannot upload image
Nothing is happning.. Toast method on post showing blank…
It is displaying “Error Uploading Image”.
my program erorr below.i cant run virtual
Description Resource Path Location Type
Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Landroid/support/v7/app/ActionBar$DisplayOptions; a Unknown Android Packaging Problem
Try cleaning your project go to build -> clean
Hi, it displays and sometimes Error Registering.
Please advise, would really appreciate your help 🙂
Blank Toast and no data uploaded in the images table in my database ….. What to do ? ?
image is not uploading toast message is saying
image is not uploading toast message is saying only
I can’t running this in database server, just running in local database
Belal Khan…How to compare these images for duplication.. as i m doing registration on the bases of thumbprints.. so how i could compare thumprints for duplication???? thanks in advance
Hi, Actually want to upload my image inside the Adapter like Recyclerview.Adapter and I initiated the views inside viewHolder. The problem is how can I override onActivityResult() inside the viewHolder or adapter?
Sorry I run the code and i have an error message like “Error Registing”
Would you mind , make tutorial for upload and download pdf,doc, etc .. Or maybe all file types .. Thank you ..
i am using this code but given error Caused by: java.lang.OutOfMemoryError: Failed to allocate a 30743478 byte allocation with 16777216 free bytes and 25MB until OOM please help me
There is a problem with the code in this example, encode image to base64 on main thread will make your app to crash.
¿How resolve error ?
android java.lang.OutOfMemoryError String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
write this code in application teg of manifest file –>
android:largeHeap=”true”
hey…can you also make a tutorial of download file/pdf from server with php and android java
Thanks for the posting. It was really a great help.
hi Ben Tumbling..
that code working ah… in have error in that an error message like “Error Registing”
I want to upload image image from my android application to server using Django web server. I created a Django file upload app.I want to connect it with android application.
How to upload multiple images to server?
Hello, That’s code works me fine. Now, I want to know how to get file size and give a condition for upload less than 1 MB size image. . . . Thank you very much for your nice tutorial.
Hey,
Can you please tell that which type of web service we are using here…
Thanks in andvance
Sir,
Could you plz do a prjt to Displaying an Image from PHP MySQL into imageview in Android using Json.
hey, i have a problem in request handler.its asking me to create a class..what should i do??? please help
Hey Brother first off all thanks to you for that code…i did it…
can u tell me how to upload multiple image on server
Go online find the really cheap yankee jerseys.
And the wholesale quality nfl womens jerseys cheap,too.
Hi,
I’ve a problem wherein, I cannot upload images above 50kb, for some reason. I’m using Godaddy server and also checked max_upload_size but it is 32M, so this should not happen right?
If you can help please?
Hi,
I’ve encountered similar problems, where the toast displayed is it might have been due to the fact that i’m using xampp server. Is it possible for it to work using xampp server and how do i make it work?
this is the error i see in my logcat everytime i press the upload button. how do I fic this?
10-02 05:55:23.373 2850-2894/com.fairoozzafar.imageuploadsample W/EGL_emulation: eglSurfaceAttrib not implemented
10-02 05:55:23.373 2850-2894/com.fairoozzafar.imageuploadsample W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe3ab2780, error=EGL_SUCCESS
I dont get any error in my android project but it shows “The imageuploadsample has stopped working”
I tried even by reinstallation but it doesnt work ….hw cn i fix it??????????
How to download???
not working 🙁
Will It work well for 3 images……should I upload them one after the other or do some other tricks. I am new to php and MySql so pls help
it display message “Error Uploading Image.”
internet connection is fine. i m using wamp server.
Hi,
thanks Belal Khan.
when i run this app on emulator. it work perfectly. but when i run it on Samsung mobile i get error (ViewRootImpl: sendUserActionEvent() mView == null ).
Kindly help me i am waiting for your response.
again thanks.
hi sir,
By using this code , can upload any file like(text,pdf,audio) , is there any solutions
Hi..I got the error:undefined index: image in php file. But it is working from Postman. Can not upload image to database from emulator.
friend is the library net.gotev:uploadservice:2.1 is free to use for commercial or not..?
hello,
it was a great tutorial, i searched for this at many sites but could not get the exact solution.
i understood your android part and its working fine but i have problem in understanding php code as i do not have any knowledge about it.
could you please provide this solution using java code.
it would be of great help!!
thanks in advance.
how it works if your column is defined as a blob and you encode the image as String ?????
Hello,
This tutorial is very very useful, it helped me a lot. I have a question Belal, onClickListener of listview it get all info about employee to other activity. but i want to this with recycleView can you help me ? i Tried the same code does work. this code in recycleView :
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewEmployee.class);
HashMap map =(HashMap)parent.getItemAtPosition(position);
String empId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}
I want in RecycleView please help me…
thx for u tutotial , you’re tutorial make me fun for try android .
can you help me to create CRUD with image?
hi…
i am getting this error
05-04 16:37:00.063 31633-32510/com.devimran.imrankhan.loadimage E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.devimran.imrankhan.loadimage, PID: 31633
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)’ on a null object reference
at com.devimran.imrankhan.loadimage.MainActivity.getStringImage(MainActivity.java:79)
at com.devimran.imrankhan.loadimage.MainActivity$1UploadImage.doInBackground(MainActivity.java:107)
at com.devimran.imrankhan.loadimage.MainActivity$1UploadImage.doInBackground(MainActivity.java:86)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
05-04 16:37:00.095 31633-32510/com.devimran.imrankhan.loadimage I/Process: Sending signal. PID: 31633 SIG: 9
my app goes crash everytime when i click on upload img button
i am getting toast br
i am using hostinger….
help me as soon as possible
Thanks a lot Belal for all the tutorials. I followed this particular tutorial and im able upload and download profile picture in the project i am currently pursuing. I have a question. Please how can I set a default picture in the android application when the user has not uploaded a profile picture?
Anxiously waiting for your reply. Thanks in advance
Thanks it’s working properly.
I have problem when I upload image to my MySQL server the null pointer exception to
Bitmap compress error occurs.
when running upload.php I am gettint error. pls help Bilal.
I used the same code and run it but theres a toast message y is it>
Hi Bilal, This is nice tutorial. I am having problem in php webservice of uploading image in database. When I am uploading image at that time null value inserted in image column and it shows message Image Uploaded Successfully. I think $_POST[‘image’] is getting empty. So, please help me.
Thank you
protected String doInBackground(Bitmap… params) {
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
have an issue with params.
what can be the solution for this?
Work like a charm. Thank you
I am getting error while uploading as your app has stopped I am using Eclipse please say
how to compare uploaded image with database image in android side