Here you will learn about android upload image to server using volley library.
At server side I have used java web service and for sending image to server volley library is used.
How it works?
- The user chooses an image from gallery and click on upload button.
- The image is then converted into Base64 string format and sent to server using volley network library.
- Now at server side this Bas64 string is converted back into image and stored at some location.
Android Upload Image to Server Using Volley
Server Code
Below is the code for server. It is a java web service. If you don’t know how to make web service in java then read below tutorial.
Also Read: Create Simple Java RESTful Web Services Using Jersey
DemoService.java
package example; import java.io.FileOutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.codec.binary.Base64; @Path("/DemoService") public class DemoService { @POST @Path("/upload") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML) public String uploadImage(@FormParam("image") String image) { String result="false"; //decode Base64 String to image try{ FileOutputStream fos = new FileOutputStream("H:/image.jpg"); //change the path where you want to save the image byte byteArray[] = Base64.decodeBase64(image); fos.write(byteArray); result="true"; fos.close(); } catch(Exception e){ e.printStackTrace(); } return result; } }
Android Project
1. Now create a new android project with package name com.androiduploadimage
2. Add dependency for volley library by adding following line in build.gradle file.
compile 'com.android.volley:volley:1.0.0'
3. Add internet access permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>
4. Add following code in respective files.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="15dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:paddingTop="15dp" tools:context="com.androiduploadimage.MainActivity" android:orientation="vertical"> <ImageView android:layout_width="match_parent" android:layout_height="200dp" android:id="@+id/image"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Choose" android:id="@+id/choose"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Upload" android:id="@+id/upload"/> </LinearLayout>
MainActivity.java
package com.androiduploadimage; import android.app.ProgressDialog; 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.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 java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { ImageView image; Button choose, upload; int PICK_IMAGE_REQUEST = 111; String URL ="http://192.168.1.101/JavaRESTfullWS/DemoService/upload"; Bitmap bitmap; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView)findViewById(R.id.image); choose = (Button)findViewById(R.id.choose); upload = (Button)findViewById(R.id.upload); //opening image chooser option choose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_PICK); startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST); } }); upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Uploading, please wait..."); progressDialog.show(); //converting image to base64 string ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); //sending image to server StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){ @Override public void onResponse(String s) { progressDialog.dismiss(); if(s.equals("true")){ Toast.makeText(MainActivity.this, "Uploaded Successful", Toast.LENGTH_LONG).show(); } else{ Toast.makeText(MainActivity.this, "Some error occurred!", Toast.LENGTH_LONG).show(); } } },new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(MainActivity.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();; } }) { //adding parameters to send @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("image", imageString); return parameters; } }; RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this); rQueue.add(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(); try { //getting image from gallery bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); //Setting image to ImageView image.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } } } }
Screenshot
You can ask your queries in comment section.
The post Android Upload Image to Server Using Volley appeared first on The Crazy Programmer.