Upload Image From Android To Php Server


upload image from android to php  upload image from android to php server upload image from android to php server stack overflow upload image android php mysql android upload image from gallery to php server android upload image to php server example android upload image to php server tutorial android upload image to php server github android upload image to php server json android upload image to php server volley android upload image to php server using retrofit php code to upload image from android how to upload image from android to php server android capture image from camera upload to server using php mysql upload image php mysql android studio android upload image file to php server android upload image php tutorial upload image from android to server using php upload image android using php
Hello friends, in this tutorial we will learn how to upload an image from android to php server. Lets go for it.

Prerequisites:

  1. Android Studio
  2. Xampp or Wamp Server (I am using Xampp here)
  3. Text Editor (I recommend to use Sublime)

Structure of the Database:

upload image from android to php  upload image from android to php server upload image from android to php server stack overflow upload image android php mysql android upload image from gallery to php server android upload image to php server example android upload image to php server tutorial android upload image to php server github android upload image to php server json android upload image to php server volley android upload image to php server using retrofit php code to upload image from android how to upload image from android to php server android capture image from camera upload to server using php mysql upload image php mysql android studio android upload image file to php server android upload image php tutorial upload image from android to server using php upload image android using php

Firstly, we use our Android Studio to make our front part ready to capture the photo and get it ready to upload on the server.

To get start with the actual code add the permissions and dependencies to make the project work properly.

Add below permissions in the Manifests file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

And add the volley dependency in the build.gradle file of the App Module.
implementation 'com.android.volley:volley:1.1.1'

So, initially we make our layout for the Main Activity. Here is the layout code that you have to develop in your project. It contains 1 Image View, 1 Edit Text and 2 Buttons (1 for choose image and another for upload image).
<?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"
    tools:context=".MainActivity">


    <ImageView
        android:layout_width="300dp"
        android:layout_height="250dp"
        android:layout_centerHorizontal="true"
        android:id="@+id/image"
        android:layout_marginTop="15dp"
        android:visibility="gone"/>
    
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/image"
        android:hint="Enter the name: "
        android:id="@+id/txtName"
        android:layout_marginTop="20dp"
        android:visibility="gone"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/chooseBtn"
        android:layout_below="@+id/txtName"
        android:text="Choose Image"
        android:layout_marginTop="25dp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/uploadBtn"
        android:layout_marginTop="15dp"
        android:layout_below="@+id/chooseBtn"
        android:text="Upload Image"/>
</RelativeLayout>

The output will be like this...
upload image from android to php  upload image from android to php server upload image from android to php server stack overflow upload image android php mysql android upload image from gallery to php server android upload image to php server example android upload image to php server tutorial android upload image to php server github android upload image to php server json android upload image to php server volley android upload image to php server using retrofit php code to upload image from android how to upload image from android to php server android capture image from camera upload to server using php mysql upload image php mysql android studio android upload image file to php server android upload image php tutorial upload image from android to server using php upload image android using php

Now, as our layout is ready lets make our java code in MainActivity.java file. The code is give below for the java file.

Here in the upload url you have to set the path of the php file we make in this tutorial as:
private String uploadUrl="http://yourIP/PATH TO THE PHP FILE from htdoc folder in XAMPP";
package e.a01.uploadimagetophp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
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.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private Button upload,choose;
    private EditText name;
    private ImageView imgView;
    private final int IMG_REQUEST=1;
    private Bitmap bitmap;
    private String uploadUrl="http://yourIP/PATH TO THE PHP FILE from htdoc folder in XAMPP";
    public static final String TAG="TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        upload=(Button)findViewById(R.id.uploadBtn);
        choose=(Button)findViewById(R.id.chooseBtn);
        name=(EditText)findViewById(R.id.txtName);
        imgView=(ImageView)findViewById(R.id.image);

        choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage();
            }
        });
        final String nameLog=name.getText().toString();
        Log.d(TAG,"Name: "+nameLog);
    }

    private void selectImage(){
        Intent intent=new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,IMG_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==IMG_REQUEST && resultCode==RESULT_OK && data!=null){
            Uri path=data.getData();
            try {
                bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),path);
                imgView.setImageBitmap(bitmap);
                imgView.setVisibility(View.VISIBLE);
                name.setVisibility(View.VISIBLE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadImage(){
        StringRequest stringRequest= new StringRequest(Request.Method.POST, uploadUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject=new JSONObject(response);
                            String Response=jsonObject.getString("response");
                            Toast.makeText(MainActivity.this,Response,Toast.LENGTH_LONG).show();
                            imgView.setImageResource(0);
                            imgView.setVisibility(View.GONE);
                            name.setText("");
                            name.setVisibility(View.GONE);
                            Toast.makeText(MainActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params=new HashMap<>();
                params.put("image",imageToString(bitmap));
                params.put("name",name.getText().toString().trim());
                return params;
            }
        };
        MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
    }

    private String imageToString(Bitmap bitmap){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
        byte[] imgBytes=byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(imgBytes,Base64.DEFAULT);
    }
}

Now we have to create another java file in which we have to write the code to add the image in the request queue to send it to the php server.
package e.a01.uploadimagetophp;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue requestQueue;
    private static Context mCtx;

    private MySingleton(Context context){
        mCtx=context;
        requestQueue=getRequestQueue();
    }

    private RequestQueue getRequestQueue(){
        if(requestQueue==null){
            requestQueue= Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return requestQueue;
    }

    public static synchronized MySingleton getInstance(Context context){
        if(mInstance==null){
            mInstance=new MySingleton(context);
        }
        return mInstance;
    }

    public<T> void addToRequestQue(Request<T> request){
        getRequestQueue().add(request);
    }
}

Now we are done with the Android part. Now we are going to create the php file which is used to fetch the data coming from the Android Studio and store it in our database.The code is shown below:
<?php
$user_name="root";
$user_pass="";
$host_name="localhost";
$db_name="dbupload";


$conn=mysqli_connect($host_name,$user_name,$user_pass,$db_name);

if($conn){
 $image=$_POST["image"];
 $name=$_POST["name"];
 mkdir("uploads/".$name);
 $upload_path="uploads/".$name."/1.jpg";
 $server_ip = gethostbyname(gethostname());
 $upload_url = 'http://'.$server_ip.'/YoutubeImageUpload/'.$upload_path;
 $sql="insert into imageinfo(name,url) values ('$name','$upload_url')";
 

 if(mysqli_query($conn,$sql)){
  
  file_put_contents($upload_path,base64_decode($image));
  echo json_encode(array('response'=>'Image Uploaded'));
 }

 else{
  echo json_encode(array('response'=>'Image Upload Fail'));
 }
}
else{
 echo json_encode(array('response'=>'Image Upload Fail'));
}
mysqli_close($conn);
?>

Happy Coding :)

Comments

Post a Comment

Popular posts from this blog

MultiSelection of Item in Recycler View

Merge Sort