bhavikkumar bhavikkumar - 3 months ago 46
Android Question

How to upload image on server using multipart using Retrofit2.0.2 library

I want to upload image with some data like userid, description of image etc.
How I can upload in multi-part.
I search on net but fail to get proper answer for latest library.
If any one know then let us share idea.

Answer

After searching bellow Code I made for uploading asset image on server we can also upload SD card image replacing asset image path to SD card path. Hope my effort for solution of this question work other people also. In My case it work fine and I complete my project purpose image uploading using Retrofit. Code is given bellow.

        file= CopyReadAssets();
    okhttp3.RequestBody requestBody=okhttp3.RequestBody.create(okhttp3.MediaType.parse("multipart/form-data"), file);
    // MultipartBody.Part is used to send also the actual file name
    body =MultipartBody.Part.createFormData("uploadfile", file.getName(), requestBody);
    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HashMap<String,String> map=new HashMap<String, String>();
            map.put("user_id","331");
            map.put("uploadfile","uploadfile");
            map.put("version_key_android","1.0");
            Call<String> call= null;
            try {
                String requestString=getWebservicejsObjRequestforvolley("createUser",map);
                Log.d("requestString==>",requestString+"");
                progressBar.setVisibility(View.VISIBLE);
                call = apiService.upload(requestString,body);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if(progressBar!=null){
                        progressBar.setVisibility(View.GONE);
                    }
                    if(response.isSuccessful()){
                        Log.d("status==>",response.body()+"");
                    }
                }
                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    if(progressBar!=null){
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });
        }
   });
}
private File CopyReadAssets() {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), "temp.jpg");
    try {
        in = assetManager.open("screen_1.jpg");
        out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
    Log.d("file==>",file.toString()+"");
    return file;
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

public String getWebservicejsObjRequestforvolley(String mMethodname, HashMap<String, String> mMap) throws JSONException {
    String retStr;
    //String strParams = null;
    // map.put("device_id", Prefs.getDeviceTokenPref(BaseActivity.this));
    JSONObject json = new JSONObject();
    if (mMap.size() > 0) {
        for (Map.Entry<String, String> e : mMap.entrySet()) {
            String key = e.getKey();
            String value = e.getValue();
            json.put(key, value);
        }
    }
    JSONObject fJson = new JSONObject();
    fJson.put("method_name", mMethodname);
    fJson.put("body", json);
    retStr = fJson.toString();
    return retStr;
}
Comments