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 : [Link]
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 [Link]
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 [Link] file
1 <?php
2
3 include_once("[Link]");
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 [Link] & [Link]
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 [Link] file.
1 <uses-permission android:name="[Link]" />
2 <uses-permission android:name="[Link].READ_EXTERNAL_STORAGE" />
3 <uses-permission android:name="[Link].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 [Link] file later.
Step 2. Needed dependencies
We require following dependencies
1 implementation '[Link]:volley:1.1.1'
2 implementation '[Link]:picasso:2.71828'
3 implementation '[Link]:dexter:5.0.0'
Add above three lines in [Link](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="[Link]
3 xmlns:tools="[Link]
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 [Link] file, write down the following coding lines
1 import [Link];
2 import [Link];
3 import [Link];
4 import [Link];
5 import [Link];
6 import [Link];
7 import [Link];
8 import [Link].Base64;
9 import [Link];
10 import [Link];
11 import [Link];
12 import [Link];
13 import [Link];
14 import [Link];
15 import [Link];
16 import [Link];
17 import [Link];
18 import [Link];
19 import [Link];
20 import [Link];
21 import [Link];
22 import [Link];
23 import [Link];
24 import [Link];
25 import [Link];
26 import [Link];
27 import [Link];
28 import [Link];
29 import [Link];
30 import [Link];
31 import [Link];
32 import [Link];
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 = "[Link]
41 JSONObject jsonObject;
42 RequestQueue rQueue;
43
44 @Override
45 protected void onCreate(Bundle savedInstanceState) {
46 [Link](savedInstanceState);
47 setContentView([Link].activity_main);
48
49 requestMultiplePermissions();
50
51 btn = findViewById([Link]);
52 imageView = (ImageView) findViewById([Link]);
53
54 [Link](new [Link]() {
55 @Override
56 public void onClick(View v) {
57 Intent galleryIntent = new Intent(Intent.ACTION_PICK,
58 [Link].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 [Link](requestCode, resultCode, data);
70 if (resultCode == this.RESULT_CANCELED) {
71 return;
72 }
73 if (requestCode == GALLERY) {
74 if (data != null) {
75 Uri contentURI = [Link]();
76 try {
77
78 Bitmap bitmap = [Link]([Link](), contentURI);
79 [Link](bitmap);
80 uploadImage(bitmap);
81
82 } catch (IOException e) {
83 [Link]();
84 [Link]([Link], "Failed!", Toast.LENGTH_SHORT).show();
85 }
86 }
87 }
88 }
89
90 private void uploadImage(Bitmap bitmap){
91
92 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
93 [Link]([Link], 100, byteArrayOutputStream);
94 String encodedImage = [Link]([Link](),
95 [Link]);
96 try {
97 jsonObject = new JSONObject();
98 String imgname = [Link]([Link]().getTimeInMillis());
99 [Link]("name", imgname);
100 // Log.e("Image name", [Link]().toString().trim());
101 [Link]("image", encodedImage);
102 // [Link]("aa", "aa");
103 } catch (JSONException e) {
104 Log.e("JSONObject Here", [Link]());
105 }
106 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest([Link], upload_URL,
107 jsonObject,
108 new [Link]<JSONObject>() {
109 @Override
110 public void onResponse(JSONObject jsonObject) {
111 Log.e("aaaaaaa", [Link]());
112 [Link]().clear();
113 [Link](getApplication(), "Image Uploaded Successfully",
114 Toast.LENGTH_SHORT).show();
115 }
116 }, new [Link]() {
117 @Override
118 public void onErrorResponse(VolleyError volleyError) {
119 Log.e("aaaaaaa", [Link]());
120
121 }
122 });
123
124 rQueue = [Link]([Link]);
125 [Link](jsonObjectRequest);
126
127 }
128
129 private void requestMultiplePermissions(){
130 [Link](this)
131 .withPermissions(
132
133 [Link].WRITE_EXTERNAL_STORAGE,
134 [Link].READ_EXTERNAL_STORAGE)
135 .withListener(new MultiplePermissionsListener() {
136 @Override
137 public void onPermissionsChecked(MultiplePermissionsReport report) {
138 // check if all permissions are granted
139 if ([Link]()) {
140 [Link](getApplicationContext(), "All permissions are granted by user!",
141 Toast.LENGTH_SHORT).show();
142 }
143
144 // check for permanent denial of any permission
145 if ([Link]()) {
146 // show alert dialog navigating to Settings
147
148 }
149 }
150
151 @Override
152 public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions,
153 PermissionToken token) {
154 [Link]();
155 }
156 }).
157 withErrorListener(new PermissionRequestErrorListener() {
158 @Override
159 public void onError(DexterError error) {
160 [Link](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 = "[Link]
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 [Link](this)
3 .withPermissions(
4
5 [Link].WRITE_EXTERNAL_STORAGE,
6 [Link].READ_EXTERNAL_STORAGE)
7 .withListener(new MultiplePermissionsListener() {
8 @Override
9 public void onPermissionsChecked(MultiplePermissionsReport report) {
10 // check if all permissions are granted
11 if ([Link]()) {
12 [Link](getApplicationContext(), "All permissions are granted by user!",
13 Toast.LENGTH_SHORT).show();
14 }
15
16 // check for permanent denial of any permission
17 if ([Link]()) {
18 // show alert dialog navigating to Settings
19
20 }
21 }
22
23 @Override
24 public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions,
25 PermissionToken token) {
26 [Link]();
27 }
28 }).
29 withErrorListener(new PermissionRequestErrorListener() {
30 @Override
31 public void onError(DexterError error) {
32 [Link](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 [Link](new [Link]() {
2 @Override
3 public void onClick(View v) {
4 Intent galleryIntent = new Intent(Intent.ACTION_PICK,
5 [Link].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 [Link](requestCode, resultCode, data);
5 if (resultCode == this.RESULT_CANCELED) {
6 return;
7 }
8 if (requestCode == GALLERY) {
9 if (data != null) {
10 Uri contentURI = [Link]();
11 try {
12
13 Bitmap bitmap = [Link]([Link](), contentURI);
14 [Link](bitmap);
15 uploadImage(bitmap);
16
17 } catch (IOException e) {
18 [Link]();
19 [Link]([Link], "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 [Link]([Link], 100, byteArrayOutputStream);
5 String encodedImage = [Link]([Link](),
6 [Link]);
7 try {
8 jsonObject = new JSONObject();
9 String imgname = [Link]([Link]().getTimeInMillis());
10 [Link]("name", imgname);
11 // Log.e("Image name", [Link]().toString().trim());
12 [Link]("image", encodedImage);
13 // [Link]("aa", "aa");
14 } catch (JSONException e) {
15 Log.e("JSONObject Here", [Link]());
16 }
17 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest([Link], upload_URL,
18 jsonObject,
19 new [Link]<JSONObject>() {
20 @Override
21 public void onResponse(JSONObject jsonObject) {
22 Log.e("aaaaaaa", [Link]());
23 [Link]().clear();
24 [Link](getApplication(), "Image Uploaded Successfully",
25 Toast.LENGTH_SHORT).show();
26 }
27 }, new [Link]() {
28 @Override
29 public void onErrorResponse(VolleyError volleyError) {
30 Log.e("aaaaaaa", [Link]());
31
32 }
33 });
34
35 rQueue = [Link]([Link]);
[Link](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 [Link]("name", imgname);
2 // Log.e("Image name", [Link]().toString().trim());
3 [Link]("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.