Skip to content Skip to sidebar Skip to footer

How To Do Upload Image With Volley Library?

I have an image and I want to upload this image to my web service using Volley library, the problem is I'm looking for a how to do it but still haven't found. I found this, but doe

Solution 1:

i am not much familier with volley, but give a try to the following code

//JSON Request

publicMySampleImageUpload() { 
    JSONRequestResponsemResponse=newJSONRequestResponse(mContext);

    Bundleparms=newBundle();
    parms.putString("key_meail", "rojesh@demo.com");
    parms.setFile("key_url", image_path);

    mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
        parms);
}

// In SetFile & getResponse code

package com.fartogram.utils;

import java.io.File;

import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;

publicclassJSONRequestResponse {

    publicJSONRequestResponse(Context cntx) {
        mContext = cntx;
    }

    private final Context mContext;
    private int reqCode;
    private IParseListener listner;

    privateboolean isFile = false;
    privateString file_path = "", key = "";

    publicvoidgetResponse(String url, final int requestCode,
            IParseListener mParseListener) {
        getResponse(url, requestCode, mParseListener, null);
    }

    publicvoidgetResponse(String url, final int requestCode,
            IParseListener mParseListener, Bundle params) {
        this.listner = mParseListener;
        this.reqCode = requestCode;

        Response.Listener<JSONObject> sListener = newResponse.Listener<JSONObject>() {
            @OverridepublicvoidonResponse(JSONObject response) {
                if (listner != null) {
                    listner.SuccessResponse(response, reqCode);
                }
            }
        };

        Response.ErrorListener eListener = newResponse.ErrorListener() {
            @OverridepublicvoidonErrorResponse(VolleyError error) {
                if (listner != null) {
                    listner.ErrorResponse(error, reqCode);
                }
            }
        };

        if (!isFile) {
            JsonObjectRequest jsObjRequest = newJsonObjectRequest(
                Request.Method.GET, url, null, sListener, 

eListener);
            MyVolley.getRequestQueue().add(jsObjRequest);
        } else {
                if (file_path != null) {
                    File mFile = newFile(file_path);
                    MultipartRequest multipartRequest = 
    newMultipartRequest(url,eListener, sListener, key, mFile, params);
                MyVolley.getRequestQueue().add(multipartRequest);
            } 
        }
    }

    publicbooleanisFile() {
        return isFile;
    }


    publicvoidsetFile(String param, String path) {
        if (path != null && param != null) {
            key = param;
            file_path = path;
            this.isFile = true;
        }
    }

}

If it works for you mark it as right :)

Solution 2:

You have to extend Request and use MultipartEntityBuilder if you wanna upload your image as a file.

publicclassImageUploadWithVolley<T> extendsRequest<T> {

    privateMultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    private final Response.Listener<T> mListener;
    private final File yourImageFile;
    protectedMap<String, String> headers;

    publicImageUploadWithVolley(String url, ErrorListener errorListener, Listener<T> listener, File imageFile)   {
        super(Method.POST, url, errorListener); 
        mListener = listener;
        yourImageFile = imageFile;        
        addImageEntity();
    }

    @OverridepublicMap<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();
        if (headers == null
                || headers.equals(Collections.emptyMap())) {
            headers = newHashMap<String, String>();
        }
        headers.put("Accept", "application/json");
        return headers;
    }

    privatevoidaddImageEntity() {
        mBuilder.addBinaryBody("give your image name", yourImageFile, ContentType.create("image/jpeg"), yourImageFile.getName());
        mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
    }

    @OverridepublicStringgetBodyContentType()   {
        String content = mBuilder.build().getContentType().getValue();
        return content;
    }

    @Overridepublic byte[] getBody() throws AuthFailureError    {
        ByteArrayOutputStream bos = newByteArrayOutputStream();
        try {
            mBuilder.build().writeTo(bos);
        } catch (IOException e){
            VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
        }        
        return bos.toByteArray();
    }

    @OverrideprotectedResponse<T> parseNetworkResponse(NetworkResponse response){
        T result = null;
        returnResponse.success(result, HttpHeaderParser.parseCacheHeaders(response));
    }

    @OverrideprotectedvoiddeliverResponse(T response) {
        mListener.onResponse(response);
    }
}

Post a Comment for "How To Do Upload Image With Volley Library?"