I was sending a request to the server with two parameters using volley request and it was working fine. Now the requirement has changed and I need to send at least one image or maximum 3 images to the server along with the other two parameters. The image must be sent as multi-part. I have following code for Getting image from gallery and storing their file paths in the list.
List<String> imagePathList = imageFilePaths;
List<MultipartBody.Part> partMap = new ArrayList<>();
for (int i = 0; i < imagePathList.size(); i++) {
Uri fileUri = Uri.parse(imagePathList.get(i));
RequestBody requestFile = RequestBody.create(
MediaType.parse(getMimeTypee(FileUtils.getFile(getContext(), fileUri).getAbsolutePath())),
FileUtils.getFile(getContext(), fileUri)
);
MultipartBody.Part body = MultipartBody.Part.createFormData("court_image[" + i + "]", FileUtils.getFile(getContext(), fileUri).getName(), requestFile);
partMap.add(body);
}
Where imageFilePaths
is an ArrayList
. The server will receive images like court_image[0]
, court_image[1]
and so on, depends on how many image paths I have in ArrayList
.
The volley request is here:
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, url1,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(mBaseAppCompatActivity, "Success", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String token = getToken();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "multipart/form-data");
return params;
}
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("terms", "true");
params.put("phone", "phoneNo");
return params;
}
};
queue.add(postRequest);
Now the thing is as I am new to the multi-part thing, with the help I am able to get the image from gallery and storing their path in ArrayList
but I don't know how to pass the multi-part data in this volley request. Please help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…