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.
I want to add 6 parametrs + base 64 image string hopw can i send with this logic
just add them in getParams() method.
added another parameter and its not working. only taking image parameter
Got out of memory Error and
E/WindowManager: Activity samplelink.imageuploadusingvolley.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41f49648 V.E….. R……D 0,0-456,144} that was originally added here.
Could you please help me to resolve this
Show me the exact code you are using and the error.
can u give me the php code ? please i really need that
For php code read this https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
And what if i want to upload file other than image ? (pdf,doc,excel dll) is this code work ?
Check this http://stackoverflow.com/questions/32262829/how-to-upload-file-using-volley-library-in-android
thanks … its a heplfull code
how to upload Multiple image using volley library in Single URL.
In getParams() method you can use parameters.put() method to add more images.
hi Neeraj,
your code working but it throw error time of img upload
“Some error occurred -> com.android.volley.ServerError”
can you help me how it can solve
I get timed out error because the encoded String is too long. Can you help me solve this
I am gating timeOut error can you help me solve this.
getting timeout exception , rest code is same but only difference is i’m passing the image and some other data in json format as shown below
protected Map getParams() throws AuthFailureError {
Map params = new HashMap();
params.put(“PartDetails”, json);
return params;
}
if i send it without selecting the image it works fine, but if i select an image then it throws timeout exception, but the entry gets uploaded in the database
Thanks so much.
very helpful…
PHP code is not available on that link you provided in comments
How can i upload multiple images from gallery ?
Some error occurred!
please help me to solve this
Thank you…
hey bro
i need a help. In my application i’m getting human signature . after that signature converted into image file on local memory. Then next i want to upload those image file by choose that images manually i ‘m want do those task . if there is any possibilities to directly upload those images into my database .
i need to add horizontal progress bar.. how can i do??
i want to upload image to server in android ,i use ‘com.theartofdev.edmodo:android-image-cropper:2.5.+’ library for cropping if i crop full image then upload it ,it give ” com.android.volley.ServerError “, and if crop it small size and upload then it upload succesfully.
please suggest some solution
how to send an only the url to server
hey hi, String image is returning null in spring mvc
(request.getParameter(“image”))
@RequestMapping(value=”/documentUpload”,method=RequestMethod.POST)
public ResponseEntity documentUpload(HttpServletRequest request,HttpServletResponse response) throws Exception
{
String image= request.getParameter(“image”);
}
String image is returning null in spring mvc!!!
how to check in postman
My request is success but i am not getting response as i want. What is the Problem
How to upload multiple images to the server using volley?
does it works for all formats of images such as .png?
Bro i am facing com.android.volley.clienterror in a specific one server please help
here is my code
@Override
protected Map getParams() throws AuthFailureError {
Map params = new HashMap();
params.put(“url”, imageString);
params.put(“name”, name.getText().toString());
return params;
}
};