0% found this document useful (0 votes)
859 views11 pages

Android Upload Image Using Volley To Server

This document discusses uploading an image to a server using Volley in Android. It describes converting the image to a Base64 string, adding required permissions, dependencies and PHP code to upload the image to a MySQL database. The Android code handles selecting an image, converting it to Base64, making a Volley request to the PHP script and displaying a success message.

Uploaded by

Ansori Sori
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
859 views11 pages

Android Upload Image Using Volley To Server

This document discusses uploading an image to a server using Volley in Android. It describes converting the image to a Base64 string, adding required permissions, dependencies and PHP code to upload the image to a MySQL database. The Android code handles selecting an image, converting it to Base64, making a Volley request to the PHP script and displaying a success message.

Uploaded by

Ansori Sori
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

Android Upload image Using Volley

To Server (PHP-MySQL)
BY EDITORIAL TEAM ·
Welcome to Android Upload image Using Volley To Server (PHP-MySQL)
Tutorial.

In this tutorial, we will upload the image to server using volley in android.

We will use PHP as a server script and MySQL as the server database.

Using volley, we can upload the image into the Base64String format to the
remote server.
If you don’t want to convert image into base64 and want to upload image as
a multipart file, then visit : https://demonuts.com/upload-image-to-server-in-
android-using-multipart-volley/
First, we will convert the image into the Base64String format and then we will
upload it using PHP web service.
This process simplifies the process of sending the image to the remote server.

Volley uses very few lines of code to complete this task, which reduces the
complexity.

View Volley Upload Image


PHP Script
Make a new PHP file and it’s name is config.php
Following is it’s code block
1 <?php
2 $host="localhost";
3 $user="your username";
4 $password="your password";
5 $db = "your db name";
6
7 $con = mysqli_connect($host,$user,$password,$db);
8
9 // Check connection
10 if (mysqli_connect_errno())
11 {
12 echo "Failed to connect to MySQL: " . mysqli_connect_error();
13 }else{ //echo "Connect";
14
15
16 }
17
18 ?>
Following is the code for the PHP script named uploadVolley.php file
1 <?php
2
3 include_once("config.php");
4
5 $json = json_decode(file_get_contents('php://input'),true);
6
7
8
9 $name = $json["name"]; //within square bracket should be same as Utils.imageName & Utils.image
10
11 $image = $json["image"];
12
13 $response = array();
14
15 $decodedImage = base64_decode("$image");
16
17 $return = file_put_contents("uploadedFiles/".$name.".JPG", $decodedImage);
18
19 if($return !== false){
20 $response['success'] = 1;
21 $response['message'] = "Image Uploaded Successfully";
22 }else{
23 $response['success'] = 0;
24 $response['message'] = "Image Uploaded Failed";
25 }
26
27 echo json_encode($response);
28 ?>

Step 1. Add Required Permissions


We need to have some permissions in this tutorial.

Add the below source code in AndroidManifest.xml file.


1 <uses-permission android:name="android.permission.INTERNET" />
2 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Three permissions are there: internet, read internal storage and write internal
storage.

Among them, internet is normal permission but we need to ask runtime


permissions for read and write external storage.

We will write the code for runtime permissions in MainActivity.java file later.

Step 2. Needed dependencies


We require following dependencies
1 implementation 'com.android.volley:volley:1.1.1'
2 implementation 'com.squareup.picasso:picasso:2.71828'
3 implementation 'com.karumi:dexter:5.0.0'
Add above three lines in build.gradle(Module: app) file of your project.
First line will enable us to use the volley library.

Second will add the classes of picasso library to load the image from URL.

Third line will help to ask for runtime permissions with dexter library.

Step 3. activity_main.xml
Now let us create the activity_main.xml file.
First of all, write down the below coding lines in activity_main.xml file.
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:tools="http://schemas.android.com/tools"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent"
6 android:orientation="vertical">
7
8 <Button
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content"
11 android:id="@+id/btn"
12 android:layout_gravity="center_horizontal"
13 android:layout_marginTop="20dp"
14 android:textAppearance="?android:attr/textAppearanceLarge"
15 android:text="Select Image and upload to server" />
16
17 <TextView
18 android:layout_width="match_parent"
19 android:layout_height="wrap_content"
20 android:text="Below image is uploaded to server"
21 android:layout_marginTop="5dp"
22 android:textSize="23sp"
23 android:gravity="center"
24 android:textColor="#000"/>
25
26 <ImageView
27 android:layout_width="300dp"
28 android:layout_height="300dp"
29 android:layout_gravity="center"
30 android:layout_marginTop="10dp"
31 android:scaleType="fitXY"
32 android:src="@mipmap/ic_launcher"
33 android:id="@+id/iv"/>
34
35 </LinearLayout>

I have taken one button, one textview and one Imageview in the above file.

When the user clicks the button, he will be asked to select the image.

Textview is telling the user that below compiler upload the image below
image.

ImageView holds that uploaded image.

Step 4. Writing Main Activity


In your MainActivity.java file, write down the following coding lines
1 import android.Manifest;
2 import android.content.Intent;
3 import android.graphics.Bitmap;
4 import android.net.Uri;
5 import android.provider.MediaStore;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.util.Base64;
9 import android.util.Log;
10 import android.view.View;
11 import android.widget.Button;
12 import android.widget.ImageView;
13 import android.widget.Toast;
14 import com.android.volley.Request;
15 import com.android.volley.RequestQueue;
16 import com.android.volley.Response;
17 import com.android.volley.VolleyError;
18 import com.android.volley.toolbox.JsonObjectRequest;
19 import com.android.volley.toolbox.Volley;
20 import com.karumi.dexter.Dexter;
21 import com.karumi.dexter.MultiplePermissionsReport;
22 import com.karumi.dexter.PermissionToken;
23 import com.karumi.dexter.listener.DexterError;
24 import com.karumi.dexter.listener.PermissionRequest;
25 import com.karumi.dexter.listener.PermissionRequestErrorListener;
26 import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
31 import java.util.Calendar;
32 import java.util.List;
33
34 public class MainActivity extends AppCompatActivity {
35
36 private Button btn;
37 private ImageView imageView;
38
39 private final int GALLERY = 1;
40 private String upload_URL = "https://demonuts.com/Demonuts/JsonTest/Tennis/uploadVolley.php";
41 JSONObject jsonObject;
42 RequestQueue rQueue;
43
44 @Override
45 protected void onCreate(Bundle savedInstanceState) {
46 super.onCreate(savedInstanceState);
47 setContentView(R.layout.activity_main);
48
49 requestMultiplePermissions();
50
51 btn = findViewById(R.id.btn);
52 imageView = (ImageView) findViewById(R.id.iv);
53
54 btn.setOnClickListener(new View.OnClickListener() {
55 @Override
56 public void onClick(View v) {
57 Intent galleryIntent = new Intent(Intent.ACTION_PICK,
58 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
59
60 startActivityForResult(galleryIntent, GALLERY);
61 }
62 });
63
64 }
65
66 @Override
67 public void onActivityResult(int requestCode, int resultCode, Intent data) {
68
69 super.onActivityResult(requestCode, resultCode, data);
70 if (resultCode == this.RESULT_CANCELED) {
71 return;
72 }
73 if (requestCode == GALLERY) {
74 if (data != null) {
75 Uri contentURI = data.getData();
76 try {
77
78 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
79 imageView.setImageBitmap(bitmap);
80 uploadImage(bitmap);
81
82 } catch (IOException e) {
83 e.printStackTrace();
84 Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
85 }
86 }
87 }
88 }
89
90 private void uploadImage(Bitmap bitmap){
91
92 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
93 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
94 String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),
95 Base64.DEFAULT);
96 try {
97 jsonObject = new JSONObject();
98 String imgname = String.valueOf(Calendar.getInstance().getTimeInMillis());
99 jsonObject.put("name", imgname);
100 // Log.e("Image name", etxtUpload.getText().toString().trim());
101 jsonObject.put("image", encodedImage);
102 // jsonObject.put("aa", "aa");
103 } catch (JSONException e) {
104 Log.e("JSONObject Here", e.toString());
105 }
106 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, upload_URL,
107 jsonObject,
108 new Response.Listener<JSONObject>() {
109 @Override
110 public void onResponse(JSONObject jsonObject) {
111 Log.e("aaaaaaa", jsonObject.toString());
112 rQueue.getCache().clear();
113 Toast.makeText(getApplication(), "Image Uploaded Successfully",
114 Toast.LENGTH_SHORT).show();
115 }
116 }, new Response.ErrorListener() {
117 @Override
118 public void onErrorResponse(VolleyError volleyError) {
119 Log.e("aaaaaaa", volleyError.toString());
120
121 }
122 });
123
124 rQueue = Volley.newRequestQueue(MainActivity.this);
125 rQueue.add(jsonObjectRequest);
126
127 }
128
129 private void requestMultiplePermissions(){
130 Dexter.withActivity(this)
131 .withPermissions(
132
133 Manifest.permission.WRITE_EXTERNAL_STORAGE,
134 Manifest.permission.READ_EXTERNAL_STORAGE)
135 .withListener(new MultiplePermissionsListener() {
136 @Override
137 public void onPermissionsChecked(MultiplePermissionsReport report) {
138 // check if all permissions are granted
139 if (report.areAllPermissionsGranted()) {
140 Toast.makeText(getApplicationContext(), "All permissions are granted by user!",
141 Toast.LENGTH_SHORT).show();
142 }
143
144 // check for permanent denial of any permission
145 if (report.isAnyPermissionPermanentlyDenied()) {
146 // show alert dialog navigating to Settings
147
148 }
149 }
150
151 @Override
152 public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions,
153 PermissionToken token) {
154 token.continuePermissionRequest();
155 }
156 }).
157 withErrorListener(new PermissionRequestErrorListener() {
158 @Override
159 public void onError(DexterError error) {
160 Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
161 }
162 })
.onSameThread()
.check();
}

Running through above Code


Consider the below coding lines
1 private final int GALLERY = 1;
2 private String upload_URL = "https://demonuts.com/Demonuts/JsonTest/Tennis/uploadVolley.php";
3 JSONObject jsonObject;
4 RequestQueue rQueue;

First line is making a final integer variable named GALLERY.

Value of GALLERY is constant that means it’s value can not be changed.
Second line is defining a String variable which holds the URL from which we
will call the web service.

This web service will get the Image as a parameter and will add the image to
the server.

Third line is making an object of the JSONObject class.


Final line is making an object of RequestQueue class.
In onCreate() method, compiler is
calling requestMultiplePermissions() method.
Code structure for requestMultiplePermissions() method is as the below
1 private void requestMultiplePermissions(){
2 Dexter.withActivity(this)
3 .withPermissions(
4
5 Manifest.permission.WRITE_EXTERNAL_STORAGE,
6 Manifest.permission.READ_EXTERNAL_STORAGE)
7 .withListener(new MultiplePermissionsListener() {
8 @Override
9 public void onPermissionsChecked(MultiplePermissionsReport report) {
10 // check if all permissions are granted
11 if (report.areAllPermissionsGranted()) {
12 Toast.makeText(getApplicationContext(), "All permissions are granted by user!",
13 Toast.LENGTH_SHORT).show();
14 }
15
16 // check for permanent denial of any permission
17 if (report.isAnyPermissionPermanentlyDenied()) {
18 // show alert dialog navigating to Settings
19
20 }
21 }
22
23 @Override
24 public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions,
25 PermissionToken token) {
26 token.continuePermissionRequest();
27 }
28 }).
29 withErrorListener(new PermissionRequestErrorListener() {
30 @Override
31 public void onError(DexterError error) {
32 Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
33 }
34 })
35 .onSameThread()
.check();
}
This method is helping us to ask for runtime permissions to the user.

Compiler will use the classes and methods of the dexter library in this
method.

Dexter library simplifies the whole scenario of runtime permissions.

We will ask for Read and Write external storage permissions in this method.

Now read the following coding lines


1 btn.setOnClickListener(new View.OnClickListener() {
2 @Override
3 public void onClick(View v) {
4 Intent galleryIntent = new Intent(Intent.ACTION_PICK,
5 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
6
7 startActivityForResult(galleryIntent, GALLERY);
8 }
9 });

Compiler will execute the above code when the user clicks on the button.

Here, compiler will first create one Intent.

This intent will lead the user to new screen.

In this screen, system will showcase all the images present in the gallery.

Now user have to select one image from this screen. When he clicks
on OK button after choosing the image, compiler will run
the onActivityResult() method.
Following is the code block for onActivityResult() method.
1 @Override
2 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3
4 super.onActivityResult(requestCode, resultCode, data);
5 if (resultCode == this.RESULT_CANCELED) {
6 return;
7 }
8 if (requestCode == GALLERY) {
9 if (data != null) {
10 Uri contentURI = data.getData();
11 try {
12
13 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
14 imageView.setImageBitmap(bitmap);
15 uploadImage(bitmap);
16
17 } catch (IOException e) {
18 e.printStackTrace();
19 Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
20 }
21 }
22 }
23 }

Here, compiler will check if user have selected one image or not.

if the value of requestCode is equals to the GALLERY (1) variable then


compiler will enter into if(requestCode == GALLERY) condition.
Now, system will first collect the URI from the data passes in
this onActivityResult() method.
Then compiler will create the Bitmap from this URI.

After that, compiler will set that bitmap into the imageview.

And then it will call the uploadImage() method.


Coding lines for uploadImage() method is as the following
1 private void uploadImage(Bitmap bitmap){
2
3 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
4 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
5 String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),
6 Base64.DEFAULT);
7 try {
8 jsonObject = new JSONObject();
9 String imgname = String.valueOf(Calendar.getInstance().getTimeInMillis());
10 jsonObject.put("name", imgname);
11 // Log.e("Image name", etxtUpload.getText().toString().trim());
12 jsonObject.put("image", encodedImage);
13 // jsonObject.put("aa", "aa");
14 } catch (JSONException e) {
15 Log.e("JSONObject Here", e.toString());
16 }
17 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, upload_URL,
18 jsonObject,
19 new Response.Listener<JSONObject>() {
20 @Override
21 public void onResponse(JSONObject jsonObject) {
22 Log.e("aaaaaaa", jsonObject.toString());
23 rQueue.getCache().clear();
24 Toast.makeText(getApplication(), "Image Uploaded Successfully",
25 Toast.LENGTH_SHORT).show();
26 }
27 }, new Response.ErrorListener() {
28 @Override
29 public void onErrorResponse(VolleyError volleyError) {
30 Log.e("aaaaaaa", volleyError.toString());
31
32 }
33 });
34
35 rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(jsonObjectRequest);

First three lines will convert the image bitmap into Base64 string format.
Then, compiler will initialize the jsonObject.

After that, compiler will create the current time in milliseconds and sets it in
string variable.

This string variable will be the unique name of the image.

Following two lines are the parameters of the web service


1 jsonObject.put("name", imgname);
2 // Log.e("Image name", etxtUpload.getText().toString().trim());
3 jsonObject.put("image", encodedImage);

First is the name of the image and the second is the image itself in BASE64
String.

Then compiler will create the object of JsonObjectRequest class and will call
the web service.
onResponse() method will be called when the web service gives any response
in the JSON format.
In the onResponse() method, compiler will clear the Volley cache.

You might also like