«

»

09 Mar

Android: Upload image to Server

I have searched lot on Internet that how to upload image from android device to server. As a result of that, I am posting this tutorial. At server side, I used PHP script. So, you need to learn basic of PHP, because PHP is used at server side to store image. Following is a scenario that indicates how image transforms from one format to another format and finally back to original format.

Now, you understand that actually, we are sending String from android device to server not the image. Android.util package does not support the functionality of base64 encoder and decoder. So what, here is the solution.

Just go to link, http://iharder.sourceforge.net/current/java/base64/ and download the zip. Extract it and find the Base64.java file. Copy it and Past it on your project. Copy it into appropriate “src” folder.
Now, refresh Package Explorer,so that Base64.java file can be included. you will get the following error “The declared package does not match the expected package”. Fix this by opening the class file and adding a package declaration that matches your project. Following is the screenshot.

Now, following is the java code that converts the image into String and sends it to Server. You can get the pdf from here.

public class upload extends Activity {

InputStream is;

@Override

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.main);

Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),

R.drawable.a1);

ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

byte [] ba = bao.toByteArray();

String ba1=Base64.encodeBytes(ba);

ArrayList<NameValuePair> nameValuePairs = new

ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("image",ba1));

try{

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new

HttpPost("http://10.0.2.2:80/android/base.php");

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity = response.getEntity();

is = entity.getContent();

}catch(Exception e){

Log.e("log_tag", "Error in http connection "+e.toString());

}

}

}

Server Side:

Now install the server. Create the file base.php. Create another file empty file test.jpg. Make sure that path of this two file will be same. At server side base.php will be executed. This PHP Script will open test.jpg file and write the binary data.
So, now you understand that test.jpg is the result of this example. Here is the PHP code, you can get the pdf from here.

<?php

$base=$_REQUEST['image'];

echo $base;

// base64 encoded utf-8 string

$binary=base64_decode($base);

// binary, utf-8 bytes

header('Content-Type: bitmap; charset=utf-8');

// print($binary);

//$theFile = base64_decode($image_data);

$file = fopen('test.jpg', 'wb');

fwrite($file, $binary);

fclose($file);

echo '<img src=test.jpg>';

?>

Do not forget to insert following permission in AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Following are the links of other Post on Android.
Android : ContextMenu & SubMenu
Android : Connecting to MySQL using PHP
Android : Sliding Drawer
Android Countdown Timer
Getting started with Android Map View: Displaying a location by Marker
Simple Progress Bar in Android using Thread
Android listview with image and text

Manage & Developed by Sptechnolab.com

70 comments

  1. dia

    Hi there! I followed the code step by step but the test.jpg is always 0KB.
    please help!

    1. bhargav

      If you are working on Linux, then change the Owner to nobody and Group to nogroup of test.jpg image. Make sure that you use proper url of php file in android. Php file and tets.jpg should be in same folder. If you still having a problem, then send me extra information.

    2. dia

      Thanks for replying!
      I’m working on windows.
      i kept trying to change the folder not to be read only, but it still shows read only
      I added on the php side a couple of lines to write to a log file located in same place with the image, and that one saves ok, so it’s not a write access on the folder.
      please let me know what else can I try.
      thanks!!!

  2. REAL HP SERVERS

    wow….That’s really great brief.That’s very helpul.Thanks a lot.

  3. vn

    Hi
    I changed the Owner to nobody and Group to nogroup of test.jpg image but the test.jpg is always 0KB.
    please help

    1. bhargav

      Reply me some information like LogCat error message.

  4. Pao|

    I get the same problem, i’m working on windows, using xampp.
    i’m using a real device (no emulator).

    These are the steps:

    1. Run application on my device.
    2. Open a navigator (chrome) and go to http://192.168.0.118/test/uploads/img/base.php
    2.1. I see on the page:
    3. Then i go to C:\xampp\htdocs\test\uploads\img , and the file test.jpg is 0kb.

    Could you share a zip file with your code?

    1. bhargav

      Make sure that you have given internet permission in AndroidManifest.xml file.
      It is not require to open a navigator, but you have to change the url of base.php file in the java code of this example. You should write original url of php file.
      In windows, it is not require to create empty test.jpg file, because php script will automatically create it.

  5. Pao

    On the previous post:
    in the step 2.1 this is what i see:
    <img src="test.jpg"/>

    I have forgotten says that im using android 2.2
    Regards!

    1. bhargav

      This example successfully woks on Android 2.2.

  6. Marco Montes

    hi, thanks a lot, its working fine, but i tried to save the binary files as blobsin a mysql db and trying to retrieve them later. it seems they are already in the db but cant find a way to show them as .jpgs… of course i have an auto imcrement Id colum to make the query. the idea is give each image a unique url , istead of replacing test.jpg file, is there a easier way???

    1. bhargav

      It is not good idea to store image in mysql as blobs. This example stores image at server side in jpg format. Now, the idea is that you can store the path of image in mysql. In windws, php script automatically creates jpg files, you do not have the worry about creating empty files. Just you have to give filename for each image in php script. Now you can query the database and have the unique path of each jpg file.

      1. Marco Montes

        yeap not a good idea handling BLOBS , first i was trying something like this to store images in files named as id’s but never worked

        $buffer=base64_decode($base);
        $filename = “images/”.$row['ID'].”.jpg”;
        $mystring = fopen($filename, ‘wb’);
        $handle = fopen($filename, ‘wb’);
        $numbytes = fwrite($handle, $buffer);
        fclose($handle);
        echo $filename;
        print ”;

        1. bhargav

          Following is the php code that retrieves image data and filename of image from android. Stores this image in ‘img’ folder. After that enters image path in database.
          <?php
          $base=$_REQUEST['image'];
          $filename=$_REQUEST['filename'];
          $buffer=base64_decode($base);
          $path = "img/".$filename.".jpg";
          $handle = fopen($path, 'wb');
          $numbytes = fwrite($handle, $buffer);
          fclose($handle);

          $conn=mysql_connect(“localhost”,”",”");
          mysql_select_db(“test”);
          $sql=”insert into IMAGE (path) values(‘ “.$path.” ‘)”;
          $r=mysql_query($sql);
          ?>

          1. Marco Montes

            woww, merci beaucoup, this blog rules!!!

          2. Handy

            hi there, my project is similiar to this, i want to save a image path to my database, it work but the file doesn’t have a name, am i missing something? does the name’s file came from the same name from image file in my sdcard? thanks

  7. dia

    Hi there. You mentioned it’s working ok for you. Are you using php on windows? Are you using Apache or IIS? I’m trying to see if it’s an issue on php side or on android.
    Did it always work for you, or you also had to do some changes?
    thanks

    1. bhargav

      I have tested this application in xampp and wamp server and it works fine.

  8. dage_java

    I can’t get it

    can you give me a zip file …

    where is the layout.xml

    I am is an new~!

    wordhao@gmail.com

  9. Marco Montes

    the process works great but it takes a while, how can we set a process dialog, or should we do this within a service?

    1. bhargav

      You can set progress dialog using following code in java,
      ProgressDialog MyDialog = ProgressDialog.show( MyActivity.this, ” ” , ” Loading. Please wait … “, true);

      to show dialog: MyDialog.show();
      to dismiss it: MyDialog.dismiss();

  10. RaymondHo

    hey man,
    your tutorial is really helpful!!!
    help my FYP a lot!
    Thank you very much!

  11. Pradeep

    Hi Bhargav,
    The code worked absolutely fine for me thank u……wat i would like to know is that can the server side script be written in jsp for this example …..if u know can u please suggest me the code…..it would be of great help…thank u in advance

  12. Akshay Nayak

    thanks a lot bhargav, its working fine after fixing a lot of errors…. :-)

  13. Akshay Nayak

    Can u please tell me how can i access the image stored in sd card rather than an image in drawable hdpi folder?

    i have tried a code but its giving force close… can u please help me out…..

    package pic.upload;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.util.Log;

    public class picture extends Activity {
    InputStream is;
    String imageFilePath;
    @Override
    public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    Bitmap bitmapOrg= BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() +”/mypic.jpg”);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte [] ba = bao.toByteArray();
    String ba1=Base64.encodeBytes(ba);
    ArrayList nameValuePairs = new
    ArrayList();
    nameValuePairs.add(new BasicNameValuePair(“image”,ba1));
    try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new
    HttpPost(“http://172.16.6.41/mobile_insurance/base.php”);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    }catch(Exception e){
    Log.e(“log_tag”, “Error in http connection “+e.toString());
    }
    }
    }

    1. bhargav

      Code works fine and successfully uploads image at server side. An error occurred, because you are not using sd card in emulator. So, create sd card and import images into sd card.

  14. Russ

    I had everything working fine as one of my very initial Android aps. When I went to re-build it the right way, I started getting errors. Now, when I try to call the Upload class, I get an error like it can’t find the class- but the error is in runtime. “Source not found.” It gives a button “Edit Source Lookup Path…” What in the world do I do?

    Great resource, though, this code. Very cool. The PHP I am using is (and works outside the Android app!):

  15. Marco Montes Neri

    hi, i got this code working fine but can’t find a way to have a toast saying “sending” cause, it seems it’s not responding, could you plese tell me where i should put the whie {… Toast.makeText… stuff, thanks again !!

    1. bhargav

      Hi, here is a link of pdf file, upload image with progress dialog

  16. Pradeep

    Hi,
    I hve tired your code….from the code it is clear that it handles response…what should be done to display the response on the client…should any changes be made in the php script..Thank u waiting for reply

    1. bhargav

      Yes, you can refer my another blog Connecting android to mysql. With the help of example in blog, you can add image path to mysql.

  17. anonimouuuus

    This fits perfectly with my plans to take over the world!! moahaha

    Really nice blog you have here, all code works 100% and feedback is awesome!
    Keep posting!!!!!!!

    thanks bhargav :-)

  18. subakar

    i got error in line String ba1=Base64.encodeBytes(ba); saying that “The method encodeBytes(byte[]) is undefined for the type Base64″ .Anyone know the soln???????? i’m using php server as back end………

    1. bhargav

      Have you past Base64.java file into your project?

      1. yuki

        Hi, I’m having the same error as subakar but I have pasted Base64.java into the src, anyone has any idea?

        1. james

          Same problem, base64.java is in the src, method is in there, no idea why it won’t work its a public method

          1. andro

            Hi, I have the same problem with subakar, those anyone have fixed it?
            I really need the solution of it. Thanks

          2. Seemas

            first remove the import of Base64
            and then again import it then this error will be fixed
            this happends because we have already imported Base64 of java libary

      2. Jen

        i had this problem too. i used this instead and it worked

        String ba1 = Base64.encodeToString(ba, 0);

        the two parameters are the byte[] and a flag. i didn’t know which default to use so i set it to 0. that might be wrong, but it works in the end :razz:

  19. arg_vedder

    Hey, this code works great! Everything goes fine when sending 50kb img, but im having some problems sending larger images (300kb or so). Besides im getting no errors, just the file does not get uploaded.
    Is there any limit sending text via httppost? maybe a connection timeout?
    thanks!

  20. subakar

    hi Yuki…check the android version u using…in android 1.6 its working fine……its not working in android 2.2, i did’t check in 2.1……..now, for me its working well….

  21. June

    1) Do you guys know how to create an original url??

    2) where should I put this base.php?? in my src??? Please, let me know thanks.

  22. Nisha

    Hii there,
    I am making an app, which should be able to send image to php server, where image is obtained, either by accessing camera by the app or access the image of gallery. Till now, I am able to access the camera, capture image,store it to gallery and send it to server nd store it there successfully. Its also able to access the gallery, select the image, however, its nt able to send it to the server; gives the “Out of memory ” error. I am really confused because, the same image, which is captured before n send to server successfully, cannot be send when selected from the gallery. Code is given below. Can anyone please, point out the error please…..

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
    case ACTIVITY_SELECT_IMAGE:
    if(resultCode == RESULT_OK){
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();

    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    String ba1 = Base64.encodeBytes(ba);
    nameValuePairs.add(new BasicNameValuePair(“image”, ba1));
    ……..
    ……..

    }
    break;

    It gives out of memory error in line:
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);

    Thanx a lot.

    1. webdevbyjoss

      Hi, I have exactly the same problem as described in your post.
      My application crashes with out of memory error on

      boolean result = bmp.compress(Bitmap.CompressFormat.JPEG, 99, fOut);

      Have you resolved this error?

  23. Fep

    Hi very good example thanks.
    I’d like to do the same but upload a video instead of an image. What would be different ?

  24. Niti (thailand)

    very useful code. thanks to u, y bhargav.

    Initially, I had problem of file was not created.

    The root cause is because of Windows7′s permission. I need to allow user of the www’s director to full control

    I use IIS w fastPHP

  25. med

    fantastic Tutorial! It works fine and at the first try! I’m currently working on our Android APP so once again! THX

  26. thilina sampath

    :smile: :smile: :smile: lot of thankx dude……..its very useful for my currently working android app..thankx again…….\m/

  27. dhaval

    i got error like :

    Error in http connection…. i try this on local server

    http://localhost/dhaval/and/base.php

  28. Handy

    thank you for ur tutorial, i’ve uploaded the image :D do you know how to retrieve it back to android? can u show me the example? thanks before

  29. chenhou90

    can i send other information of the image to php, like for example date the picture is taken?

    1. bhargav

      Yes, you can send other information. Here is a link of nice blog. It will help you to send data with image as well.

  30. ajimukhlis

    Ow thanks man, it really works :D

  31. Raja

    hello all….can1 anyone tell me whr was d image reciding which is being sent…wat is the name of the image in the above code….m a newbie..a bit confused…plz help… :sad:

  32. Leffy

    I am having the same issue as described earlier by arg_vedder.
    This code works fine if I try to upload smaller files, however once I go above ~100kb this no longer works and I am not sure why.
    Also compression is not an option for me as it would reduce the image quality too much so I am looking for an alternative solution.

  33. Eric

    I am having the same issue as described earlier by arg_vedder.

    I’m not sure if it’s because the decode file have a size limitation…I guess I need to check for file size first before decoding it?

  34. wangpeng

    i copy you code,sometimes is good,sometimes i am use other phone is not good,in moto 2.1 always good,samsung not always run well

  35. sanjay

    Hi

    i m new to android development
    can you provide me full source for capture and upload project

    Thanks

  36. Matej

    Hi! There are two libraries for InputStream:
    a) java.io.InputStream;
    b) [your.package.name].Base64.InputStream;

    Which one should I use for InputStream is; ? :)

  37. Jahanzaib

    Hi this Tutorial is great.

    I can successfully send data to the server can you tell me after receiving the same data i am unable to convert that same data into bitmap.

    Can you please tell me how to convert String(string from server) of an image into bitmap , So i can easily set this bitmap into Image View.

  38. Kevin

    Thanks! works great! I had to change the line of code so it reads

    String ba1 = Base64.encodeToString(ba, 0);

    but everything else was flawless. Nice work.

  39. Madhavan

    Very very thanks to u……… it works well and images stored in the server… path is stored in the mysql db..

  40. Mahmoud

    the code is worked for me but can i return image url instead of image bitmap?

  41. Muhammad Sohail

    i have copied and pasted your code and made many corrections but still there is one error plz help
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
    R.drawable.a1);

    error is: a1 cannot be resolved or is not a field

    1. Farooq Arshed

      I have got the same problem. Please respond. :sad:

  42. cvd

    how can I upload an image from an imageview from the layout xml? similarly like findviewbyid.imgid

    My layout name is main.xml and image id is imgid

    kindly help me…

  43. chand

    How can I upload the image from the gallery?

  44. ganesh

    hi ! can anyone suggest me java alternative for above used php script on server side.
    Any help will be appreciated..

  45. Amit Suri

    Hi Everyone
    I am new in Android and i have a task:-
    1. Allow users to Capture an image.
    2. Send that image to Web Server or Remote Server.
    My Server path is(IP address>C:>Folder(Inside this folder save captured images))

    Please anyone help me and give me complete source code or tell URL from where i can get needful Source,
    It’s very urgent.
    My email id is:andoid.amitsuri@gmail.com
    Thnx in advance

    Thanks
    Amit Suri

  46. tasnim ahmed

    Successfully posted image to the server.but took so much time

Leave a Reply

Your email address will not be published. Required fields are marked *


× 2 = twelve

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>