4

Good day! I am trying to search for a basic tutorial of uploading an image file from Android to an online MySQL database, but I can't find any.

I am now making an activity that can upload a user's profile picture from the Android to the online server.

What I need is like displaying a button and when it's clicked, a user can choose an image from the files. Can someone guide me on doing this? Thanks in advance!

JetPro
  • 1,044
  • 3
  • 23
  • 43
  • 1
    Trying to search... and what have you tried, till now ? – Lucifer Jul 25 '12 at 05:54
  • you can follow this tutorial, it must be help to you [Upload image](http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/) [image upload Activity](http://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/) – Furqi Jul 25 '12 at 05:58

2 Answers2

2

On the Client Side,You can Do this.

HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;    

String pathToOurFile = "path of the image.jpeg";
String urlServer = "http://xxx.xxx.xxx.xxx/uploader.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try {
        FileInputStream fileInStream = new FileInputStream(new File(pathToOurFile) );

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

       // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

        outputStream = new DataOutputStream( connection.getOutputStream() );
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0)
        {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = connection.getResponseCode();
        serverResponseMessage = connection.getResponseMessage();

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
    }
    catch (Exception ex)
    {
        //Exception handling
    }

Server side

<?php
    $target_path  = "./";
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
         echo "Success";
    } else{
        echo "Error";
    }
?>
Abhilasha
  • 929
  • 1
  • 17
  • 37
Haresh Chaudhary
  • 4,390
  • 1
  • 34
  • 57
1

Use following code to fetch image from ImageGallery:

Intent i = new Intent(Intent.ACTION_PICK,
               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 

It will start ImageGallery, now you can select an image, and in onActivityResult you can decode the image into bitmap, as explained in the link: here:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.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 yourSelectedImage = BitmapFactory.decodeFile(filePath);
        }
    }
}

Next you need to upload that bitmap to server. To do so you can use Haresh's solution.

Community
  • 1
  • 1
jeet
  • 29,001
  • 6
  • 52
  • 53