Android Volley Library: How to send an image to the server?

Guy guys!

I have a jpg image stored on my device and I want sent it to server (mywebsite.com/api.php). I would like to use the volley library because it is made by official Android developers from Google, and I think they will add it to sdk as soon as possible.

Now I use the following code to send strings to the server:

  postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { // code here for response } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // code here for error response } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); // the POST parameters: params.put("key", "myApiKey"); params.put("data","stringOfMyData"); return params; } }; 

How can I send jpg to a volleyball library server? Every time I send something, I need to send it along with the API key in order to receive information on the server, so I can not change Map<String, String> to Map<String, File> , because my API key is this is a string.

I read that there is a solution to change my image to a byte[] array and then convert it to a base64 string format, but I would like to avoid this if possible.

Is there any other solution for sending an image without converting it to a base64 string ?

Any recommendations or tips are welcome! Thanks in advance!

+4
source share
1 answer

Files are sent using multipart support in a POST request. This is the same as in HTML forms.

Volley does not support multiple support by default, but it is flexible, so you can extend its Request class to implement its own version of multipart .

You can find one implementation of the MultipartRequest class from this value and simply use https://gist.github.com/ishitcno1/11394069 in your program

You can use this class as follows:

  HashMap<String, String> params = new HashMap<String, String>(); String url = "YOUR POST URL"; String image_path = "your local image path"; params.put("your_extra_params", "value"); MultipartRequest multipartRequest = new MultipartRequest(url, params, image_path, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e(TAG, "Success Response: " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error.networkResponse != null) { Log.e(TAG, "Error Response code: " + error.networkResponse.statusCode); try { } if (error instanceof NetworkError) { } else if (error instanceof ServerError) { } else if (error instanceof AuthFailureError) { } else if (error instanceof ParseError) { } else if (error instanceof NoConnectionError) { } else if (error instanceof TimeoutError) { } } }); requestQueue.add(multipartRequest); 
+3
source

All Articles