Android Image to PHP Server Upload

Schalte Sprache zu: de German

Android Image Upload

This example explains how to send an image to the a php server with Android. First the photo has to be selected via an "ImagePicker". When the image is selected in the gallery, the app displays the absolute path from the photo on the filesystem. The upload-button is now green. When the upload-button is pressed, the image will start to upload. A "Loading Spinner" appears until the upload has been completed or an error occurs. After the upload the result from the server or a error message is displayed in the TextView. The data transmission uses HTTP-POST to send the image to the server. The code also support HTTPs. First you should check that the data access is activated in the settings

PHP Server

On the server side is a simple PHP script, which takes the POST-File and stores it on the file system in the IMG folder. A log file (log.txt) is also created on the server that stores the time and file name.The PHP script needs the permission to write files to the server. It may happen that image files larger than 2 megabytes can not be uploaded.To configure this, "upload_max_filesize" & "post_max_size" has to be changed in the PHP configuration. The PHP script also checks if the file is a photo (JPG, PNG). If it is a different file type, the file will not be saved. You can also use our test server for the first test. The link to the photo shows the app, if it runs with the URL of our test server. This code is located in the MainActivity.

package com.aeqweb.imagesend;

import ...

public class MainActivity extends Activity {
    Button selectButton, uploadButton;
    TextView view_status;
    ProgressDialog progress;
    String response;
    String realPath;
    String UPLOAD_SERVER = "";
    protected void onCreate(Bundle savedInstanceState) {
        view_status = (TextView) findViewById(;
        view_status.setText("Select your Image");
        selectButton = (Button) findViewById(;
        selectButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
        selectButton.setOnClickListener( new View.OnClickListener() {
            public void onClick(View v) {
                //Open image selector
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 0);
                selectButton.getBackground().setColorFilter(0xffd6d7d7, PorterDuff.Mode.MULTIPLY);

        uploadButton = (Button) findViewById(;
        uploadButton.setOnClickListener( new View.OnClickListener() {
            public void onClick(View v) {
                //Open image selector
                SendImage start_task = new SendImage();
                view_status.setText("Try to upload Image");

    protected void onActivityResult(int reqCode, int resCode, Intent data) {
        if(resCode == Activity.RESULT_OK && data != null){
            // Check the SDK Version
            if (Build.VERSION.SDK_INT < 11)
                realPath = PathOfImage.PathAPI11(this, data.getData());
            else if (Build.VERSION.SDK_INT < 19)
                realPath = PathOfImage.Path_API18(this, data.getData());
                realPath = PathOfImage.Path_API19(this, data.getData());
            view_status.setText("Image path: " + realPath + "\n\nYou can start the upload now");
            uploadButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);

    public class SendImage extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
            progress = new ProgressDialog(MainActivity.this);
            progress.setMessage("Please wait until the process is finished");
            progress.setCancelable(false); // disable dismiss by tapping outside of the dialog


        protected Void doInBackground(Void... params) {
            try {
                response = POST_Data(realPath);
            } catch (Exception e) {
                response = "Image was not uploaded!";
            return null;

        protected void onPostExecute(Void result) {
            uploadButton.getBackground().setColorFilter(0xffd6d7d7, PorterDuff.Mode.MULTIPLY);

    public String POST_Data(String filepath) throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;
        String boundary =  "*****"+Long.toString(System.currentTimeMillis())+"*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        String[] q = filepath.split("/");
        int idx = q.length - 1;
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);
        URL url = new URL(UPLOAD_SERVER);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes("--" + boundary + "\r\n");
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "img_upload" + "\"; filename=\"" + q[idx] +"\"" + "\r\n");
        outputStream.writeBytes("Content-Type: image/jpeg" + "\r\n");
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + "\r\n");
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, 1048576);
        buffer = new byte[bufferSize];
        bytesRead =, 0, bufferSize);
        while(bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, 1048576);
            bytesRead =, 0, bufferSize);
        outputStream.writeBytes("--" + boundary + "--" + "\r\n");
        inputStream = connection.getInputStream();
        int status = connection.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
            return response.toString();
        } else {
            throw new Exception("Non ok response returned");
} This file determines the correct path for the image.

package com.aeqweb.imagesend;

import ...

public class PathOfImage {

    public static String Path_API19(Context context, Uri uri) {
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);
        String id = wholeID.split(":")[1];
        String[] column = {MediaStore.Images.Media.DATA};
        String sel = MediaStore.Images.Media._ID + "=?";
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{id}, null);
        int columnIndex = cursor.getColumnIndex(column[0]);
        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        return filePath;

    public static String Path_API18(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        String result = null;
        CursorLoader cursorLoader = new CursorLoader(
                contentUri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();
        if (cursor != null) {
            int column_index =
            result = cursor.getString(column_index);
        return result;

    public static String PathAPI11(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index
                = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        return cursor.getString(column_index);

In the manifest you must enable the permission to access the file system and the Internet.

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

Von Alex @ AEQ-WEB 176