1

How do i send a file(data) from a mobile device to server using volley library.

here i have listed my param below please help me to solve this.

        Map<String, String> mHeaderPart= new HashMap<>();
            mHeaderPart.put("Content-type", "multipart/form-data;");
            mHeaderPart.put("Authorization", authorizationKey);


    //String part
            Map<String, String> mStringPart= new HashMap<>();
            mStringPart.put("candidate_id", SessionStores.getBullHornId(getActivity()));
            mStringPart.put("externalID", "portpolio");
            mStringPart.put("fileCount", "2");//number of files
            mStringPart.put("fileType", "SAMPLE");
            mStringPart.put("platform", "android");

//file param

     Map<String, File> mFilePartData= new HashMap<>();

In above file param i have to add n number of files and sent it to the server. How do i get file from device and add n number of files with param and sent it to the server if anyone could you please give me suggestion.

And if anyone have example of sending multiple files with param using volley please guide me. Thanks in advance.

karthik
  • 321
  • 1
  • 8
  • 21
  • Possible duplicate of [How to do upload image with Volley library?](http://stackoverflow.com/questions/27112694/how-to-do-upload-image-with-volley-library) – Nitesh Sep 29 '16 at 09:34
  • Checkout for example [Stackoverflow Link](http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley) [Stackoverflow Link](http://stackoverflow.com/questions/32262829/how-to-upload-file-using-volley-library-in-android) – mpals Sep 29 '16 at 09:36
  • thanks for you reply @Nitesh, mplas. I have doubt how to send filecontent param as an array for multiple files sending. Like filecontent0,filecontent1/ Here filecontent is file param for adding file. – karthik Sep 29 '16 at 11:24
  • you have to upload all files individually and then attach their ids with the actual post .. i don't think there is a way to upload all files together. – Nitesh Sep 29 '16 at 11:49

1 Answers1

0

Volly don't provide direct way to upload file on server using multi part.

For uploading multiple files using volly follow below steps:

Step 1: Create a new Class named MultipartRequest.java that extends Request from volly like below:

import com.android.volley.AuthFailureError;

import com.android.volley.NetworkResponse;

import com.android.volley.ParseError;

import com.android.volley.Request;

import com.android.volley.Response;

import com.android.volley.VolleyLog;

import com.android.volley.toolbox.HttpHeaderParser;

import org.apache.http.HttpEntity;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.FileBody;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.Map;

public class MultipartRequest extends Request<String> { private MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); HttpEntity entity;

    private HashMap<String, File> sendFile = new HashMap<>();

    /**
    * 
    * @param url               url
    * @param errorListener     volly error listenere
    * @param sendFile          HashMap with key as file name and value as file  object
    */

    public MultipartRequest(String url, Response.ErrorListener errorListener,   HashMap<String, File> sendFile) {
    super(Method.POST, url, errorListener);

    this.sendFile = sendFile;
    buildMultipartEntity();
    entity = entitybuilder.build();
    }

    private void buildMultipartEntity() {

    if (sendFile != null)
        for (Map.Entry<String, File> entry : sendFile.entrySet()) {
            entitybuilder.addPart(entry.getKey(), new    FileBody(entry.getValue()));

            // here you can set key as filename
            // value will be the file object to be upload

        }
    }

    @Override
    public String getBodyContentType() {
    return entity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        entity.writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
    try {
        String json = new String(
                networkResponse.data,   HttpHeaderParser.parseCharset(networkResponse.headers));
        return Response.success(json, HttpHeaderParser.parseCacheHeaders(networkResponse));

    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    }
    }

    @Override
    protected void deliverResponse(String s) {

    //Your response

    }
}

step 2:

From your activity:

public void executeMultipart(String url,HashMap<String, File> fileData) { 
    try { MultipartRequest mRequest = new MultipartRequest(url , new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) {

            }
        },fileData);
        mRequest.setRetryPolicy(new DefaultRetryPolicy(
                (int) TimeUnit.SECONDS.toMillis(20),
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    } catch (Exception e) {
        e.printStackTrace();
    }
    }

step 3: In your app build.gradle file add:

compile('org.apache.httpcomponents:httpmime:4.3.6') { exclude module: 'httpclient' }

Note: From API 22 org.apache.http.HttpEntity is deprecated , so better to use either URLConnection or you can use retrofit library both have thier own advantages and disadvantages

nurgasemetey
  • 752
  • 3
  • 15
  • 39
Patrick R
  • 6,621
  • 1
  • 24
  • 27