android image upload to server

      Comments Off on android image upload to server

android image upload to server

android image upload to server

android image upload to server is most frequently used functionality in any android app. Here is step by step guide for uploading image to a server with easy steps. Here i have compiled code after referring many websites and testing. My code includes only 2 part.

Part 1 : Java Code to send an image to the Server.

Part 2 Fetch image name from Database and display it using Picasso.

XML Code for Displaying current photo and select photo options.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ProfilePhoto"
    tools:showIn="@layout/activity_profile_photo">
    <!-- <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Choose Image"
       android:id="@+id/buttonChoose" />-->


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonUpload"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:src="@mipmap/ic_launcher" />


    <Button
        android:id="@+id/buttonUpload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="46dp"
        android:background="@color/colorPrimary"
        android:textAppearance="?android:textAppearanceMediumInverse"
        android:text="UPDATE"/>
</RelativeLayout>

 

Code Sample of Java File to Upload Photo using AsyncTask

package my.package.image.upload.in;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.Map;

public class ProfilePhoto extends AppCompatActivity implements View.OnClickListener {
    public static final String PREFS_NAME = "Preference";
    private Button buttonChoose;
    private Button buttonUpload;
    private ImageView imageView;
    private EditText editTextName;
    private Bitmap bitmap;
    private int PICK_IMAGE_REQUEST = 1;
    private String UPLOAD_URL = "http://website.com/folder/uphoto.php";
    private String KEY_IMAGE = "image";
    private String KEY_NAME = "mobile";
    private String extension;
    ProgressDialog pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_photo);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //buttonChoose = (Button) findViewById(R.id.buttonChoose);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);


        imageView = (ImageView) findViewById(R.id.imageView);

        //buttonChoose.setOnClickListener(this);
        imageView.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);

        SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        final String strUsername = settings.getString("mobile", "");
        final String strpass = settings.getString("password", "");
        pDialog = new ProgressDialog(ProfilePhoto.this);
        pDialog.setMessage("Loading...");
        pDialog.show();
        new FetchProfilePic().execute(strUsername, strpass);

    }


    public String getStringImage(Bitmap bmp) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (extension.equals(".jpeg")) {
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        } else if (extension.equals(".png")) {
            bmp.compress(Bitmap.CompressFormat.PNG, 50, baos);
        } else if (extension.equals(".jpg")) {
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        } else {
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        }


        byte[] imageBytes = baos.toByteArray();
        return Base64.encodeToString(imageBytes, Base64.DEFAULT);

    }

    private void uploadImage() {
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        //Disimissing the progress dialog
                        loading.dismiss();
                        //Showing toast message of the response
                        Toast.makeText(getApplicationContext(), "Photo Updated", Toast.LENGTH_LONG).show();

                        SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                        String strUsername = settings.getString("mobile", "");
                        String strpass = settings.getString("password", "");

                        new FetchProfilePic().execute(strUsername, strpass);

                        //finish();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Dismissing the progress dialog
                        loading.dismiss();
                        finish();


                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Converting Bitmap to String
                String image = getStringImage(bitmap);

                SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
                String strusername = settings.getString("mobile", "");

                //Creating parameters
                Map<String, String> params = new Hashtable<String, String>();

                //Adding parameters
                params.put(KEY_IMAGE, image);
                params.put("filename", strusername + extension);
                params.put(KEY_NAME, strusername);

                //returning parameters
                return params;
            }
        };

        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Profile 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) {
            Uri filePath = data.getData();

            ContentResolver cR = getApplicationContext().getContentResolver();
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = "." + mime.getExtensionFromMimeType(cR.getType(filePath));


            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {

        if (v == imageView) {
            showFileChooser();
        }

        if (v == buttonUpload) {

            uploadImage();
        }
    }

    //==================================================================
    // FetchDataFromPref
    //==================================================================
    public class FetchProfilePic extends AsyncTask<String, Void, String> {

        @Override
        protected void onPostExecute(String json) {

            try {
                pDialog.dismiss();
                pDialog = null;
            } catch (Exception e) {
                e.printStackTrace();
            }


            if (json == null) {
                return;
            }

            try {

                JSONObject js = new JSONObject(json);
                JSONArray user = js.getJSONArray("item");


                for (int i = 0; i < user.length(); i++) {
                    JSONObject j2 = user.getJSONObject(i);


                    String profilurl = j2.get("p2").toString();



                    try {


                        Picasso.with(ProfilePhoto.this)
                                .load("http://website/folder/photolocation/" + profilurl)
                                .memoryPolicy(MemoryPolicy.NO_CACHE)
                                .networkPolicy(NetworkPolicy.NO_CACHE)
                                .into(((ImageView) (findViewById(R.id.imageView))));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                }

            } catch (JSONException js) {
                js.printStackTrace();
            }

            // return;

        }

        @Override
        protected String doInBackground(String... params) {
            String tempdata = "";
            String buffer = "";


            try {


                String tt = "http://website/folder/gphoto.php";
                String u = tt + "?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20");
                URL url = new URL(u);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.connect();

                InputStream is = conn.getInputStream();
                if (is == null) {
                    return tempdata;
                } else {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line = "";

                    while ((line = reader.readLine()) != null) {
                        buffer += line;
                    }
                    return buffer;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return buffer;
        }
    }

}

PHP Webservice for fetching photo Name from database to display using Picasso

Filename : gphoto.php

<?php
	include("connect.php");

	$response = array();
	$posts = array();
	
	//mobile pass
	$par1=$_GET['p1'];
	$par2=$_GET['p2'];
	
	$eve_veri = "select profilepic,bname,email from user_master where mobile='$par1' and password='$par2'";
	
	$re_veri = mysqli_query($conn, $eve_veri);
	
	
	while($rtveri = mysqli_fetch_assoc($re_veri))
	{
		
		
		$profilepic = $rtveri['profilepic'];
		$bname = $rtveri['bname'];
		$email = $rtveri['email'];
		
			
		$result="1";
		
		
		$posts[] = array('p1'=> $result,'p2'=> $profilepic,'p3'=> $bname,'p4'=> $email);

		$response['posts'] = $posts;
		echo stripslashes(json_encode( array('item' => $posts)));
		return;
	}
		
$result="0";
$posts[] = array('p1'=> $result,'p2'=> "nophoto.png");

$response['posts'] = $posts;
echo stripslashes(json_encode( array('item' => $posts)));		
		
 
 
 
 
 ?>

PHP Webservice to upload file to server.

Filename : uphoto.php

<?php
 
 // mobile photo
 include("connect.php");
 
 if($_SERVER['REQUEST_METHOD']=='POST')
 {
 
	$image = $_POST['image'];
	$name = $_POST['mobile'];
	$filename = $_POST['filename'];
	
	
	$path = "./photofoldername/$filename";
	
	file_put_contents($path,base64_decode($image));
 
	$eve2 = "update user_master set profilepic='$filename' where mobile='$name'";
	
	$re = mysqli_query($conn, $eve2);

 
 
	$result="1";
	$msg="Photo Updated";
		
	$posts[] = array('p1'=> $result,'p2'=> $msg);
	
	$response['posts'] = $posts;
	echo stripslashes(json_encode( array('item' => $posts)));

 
 }
 
 
 ?>

Save

Save

Save

Save