Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

java - Send Images as Multipart with Other Params in Volley Request

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Though this is an old question, I thought I should post my answer here as I was having the same problem and could manage to solve that.

For uploading the image along with some other parameters, I used volley. However, I found a wrapper of the original volley library which is easier to integrate for multi-part requests. Hence I added the following library in the build.gradle file.

dependencies {
    compile 'dev.dworks.libs:volleyplus:+'
}

I removed the original volley library from my build.gradle and used the above library instead which can handle both multi-part and normal requests having similar integration technique.

Then I just had to write the following class which handles the POST request operation.

public class POSTMediasTask {
    public void uploadMedia(final Context context, String filePath) {

        String url = getUrlForPOSTMedia(); // This is a dummy function which returns the POST url for you
        SimpleMultiPartRequest multiPartRequestWithParams = new SimpleMultiPartRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Response", response);
                        // TODO: Do something on success
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO: Handle your error here
            }
        });

        // Add the file here
        multiPartRequestWithParams.addFile("file", filePath);

        // Add the params here
        multiPartRequestWithParams.addStringParam("terms", "SomeTerms");
        multiPartRequestWithParams.addStringParam("phone", "85050055055");

        RequestQueue queue = Volley.newRequestQueue(context);
        queue.add(multiPartRequestWithParams);
    }
}

Now execute the task like the following.

new POSTMediasTask().uploadMedia(context, mediaPath);

You can upload one file at a time using this library. However, I could manage to upload multiple files, just by initiating multiple tasks.

Hope that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...