Image upload to PHP server from Android code

Image upload to PHP server from Android code. UploadImagesTask.java is POST request to upload image from android application to remote server. In current example is PHP server.

public class UploadImagesTask extends AsyncTask<Void, Void, String> {

    private final UploadTaskListner listner;
    private final Bitmap photo;

    public UploadImagesTask(UploadTaskListner listner, Bitmap photo) {
        this.listner = listner;
        this.photo = photo;
    }

    @Override
    protected String doInBackground(Void... voids) {
        HttpURLConnection connection = null;
        String response = null;
        try{
            URL url  = new URL( "API");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty( "charset", "utf-8");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();

            String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            String urlParameters  = "image=" + encodedImage;

            byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
            int postDataLength = postData.length;
            connection.setRequestMethod("POST");
            connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
            connection.setUseCaches( false );

            connection.connect();
            try( DataOutputStream wr = new DataOutputStream( connection.getOutputStream())) {
                wr.write( postData );
            }
            InputStream inputStream = connection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            BufferedReader reader = null;
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            response = buffer.toString();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            connection.disconnect();
        }
        return response;
    }

    @Override
    protected void onPostExecute(String status) {
        if( status!=null &amp;&amp; status.length() > 0 )
            listner.onUploadComplete("Images uploaded successfully.");
    }
}

Async task call back listener

public interface UploadTaskListner {
    void onUploadComplete(String status);
}

MainActivity.java will invoke image upload task by passing the bitmap object.

public class MainActivity extends AppCompatActivity implements UploadTaskListner{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // init code
        UploadImagesTask task = new UploadImagesTask(this, bitmap);
        task.execute();
    }
    @Override
    public void onUploadComplete(String status) {
        
    }
}

PHP code to save image in POST request call. Images is save in current directly with randomly generated name.

<?php

if ( isset($_POST['image']) ) {

$image = str_replace('data:image/png;base64,', '', $_POST['image']);
$image = str_replace(' ', '+', $image);
// Decode the Base64 encoded Image
$data = base64_decode($image);
// Create Image path with Image name and Extension
$file = 'images/' . generateRandomString(15) . '.jpg';

$success = file_put_contents($file, $data);
echo $success;
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

?>

Image upload to PHP server from Android code.

Also check : http://www.unbounded.in/image-download-from-server-android-code/

(Visited 28 times, 1 visits today)

PrAkAsH

Eyeing investment. Please note that the views given in this website are meant for reference and guidance of the readers to explore further on the topics and take informed decisions. These should not be construed as investment advice or legal opinion.

You may also like...

1 Response

  1. January 11, 2019

    […] jQuery( function($){ if ( $('#flexslider-featured').length ) { $('#flexslider-featured').on('featured-slider-ready', function() { $( '#5c37f0423ff5e' ).animateSvg(); }); } else { $( '#5c37f0423ff5e' ).animateSvg( { svg_opacity : 0.3, filter_opacity : 0.5 } ); } }); 0 […]

Leave a Reply

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

Solve : *
25 × 11 =