I am trying to upload an image to server using volley, I followed some tutorials but in my case, I need to pass the multipart data in the body of the post request.
private void uploadBitmap(final Bitmap bitmap) throws JSONException {
//our custom volley request
String URL = "https://<---------->/me/avatar";
JSONObject jsonBody = new JSONObject();
jsonBody.put("avatar", new VolleyMultipartRequest.DataPart( "index.png", getFileDataFromDrawable(bitmap)));
final String requestBody = jsonBody.toString();
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
loading.setVisibility(View.GONE);
Toast.makeText(ProfileSettings.this, "Image uploaded successfully", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = new JSONObject(new String(response.data));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Bearer " + jsonToken);
return params;
}
@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("avatar", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
@Override
public byte[] getBody() throws AuthFailureError {
return requestBody.getBytes();
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
I got this code from tutorials, but they are giving 500 error, so I guess this may be because I need to pass "avatar": "index.png" in the body of the request and not this way.