Search code examples
javaandroidandroid-volleymultipart

Uploading multiple images with volley?


I have gone through a lot of post in SO and other tuts as well.But i couldn't get any latest official or other post that doesn't contain any deprecated code for uploading multiple images using volley.I came to know Apache HTTP Client removal and related in new android M and preferred to use below instead.

android {
    useLibrary 'org.apache.http.legacy'
}  

So, can any one help me out for doing multiple image upload with new updated deprecated less volley class ?


Solution

  • You can use the latest version of volley from here.It's an unofficial mirror with some minor bug fix and the source code will synchronize periodically with the official volley repository.

    for Gradle

    compile 'com.mcxiaoke.volley:library:1.0.19' 
    

    or you can download the compiled version from here

    Now you can use the below attached class for making multipart request using volley by the help of MultipartEntityBuilder in org.apache.http.entity.mime without having any deprecated code.

    CustomMultipartRequest.java

    Sample usage

    //Auth header
    Map<String, String> mHeaderPart= new HashMap<>();
    mHeaderPart.put("Content-type", "multipart/form-data;");
    mHeaderPart.put("access_token", accessToken);
    
    //File part
    Map<String, File> mFilePartData= new HashMap<>();
    mFilePartData.put("file", new File(mFilePath));
    mFilePartData.put("file", new File(mFilePath));
    
    //String part
    Map<String, String> mStringPart= new HashMap<>();
    mStringPart.put("profile_id","1");
    mStringPart.put("imageType", "ProfileImage");
    
    CustomMultipartRequest mCustomRequest = new CustomMultipartRequest(method, mContext, url, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    listener.onResponse(jsonObject);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    listener.onErrorResponse(volleyError);
                }
            }, mFilePartData, mStringPart, mHeaderPart);
    

    Either you can use httpmime-4.3.5.jar and httpcore-4.3.2.jar for getting access of MultipartEntityBuilder and other methods which is used to make the request or add the following in your gradle if your targeting API 23 and above.

    android {
        useLibrary 'org.apache.http.legacy'
    }  
    

    Any way I'm using the mentioned jar's and it's works like a charm in Android M also.

    Update

    Please note, com.mcxiaoke.volley:library:1.0.19 deprecated and no longer being maintained, please use official version from jCenter.

    compile 'com.android.volley:volley:1.0.0'