user2849146 user2849146 - 2 months ago 39
JSON Question

Retrofit2: Upload an Image with some Form Data-Android

The PostMan screenshot

The above screenshot contain the Post method and Response from the server..
here i am trying to upload an image with some data to my server(catch the image from gallery or camera)..

I am trying to achieve this via retrofit2.
trying some methods from Internet... but i can't get the right way to done it

new in retrofit2. so I cant done this.


How to Create retrofit2 interface and handle the response..
please help

Edit My Try


Code in Activity

ProofAPI service = retrofit.create(ProofAPI.class);
File file=new File(sdCard.getAbsolutePath()+fNameAd);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("proof", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

HashMap<String, String> map = new HashMap<>();
map.put("userId", user_id);
map.put("proofDocId", idproofno);
map.put("proofFilename", proofFilename);
map.put("docType", docType);
Call<ProofResp> call = service.uploadFileWithPartMap(map,filePart);
call.enqueue(new Callback<ProofResp>() {
@Override
public void onResponse(Call<ProofResp> call, Response<ProofResp> response) {
Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<ProofResp> call, Throwable t) {
Toast.makeText(getApplicationContext(),"fjkds",Toast.LENGTH_SHORT).show();
}
});



Retofit2 Interface -> ProofAPI


@Multipart
@POST("rest-proof-upload")
Call<ProofResp> uploadFileWithPartMap(
@PartMap() Map<String, String> partMap,
@Part MultipartBody.Part file
);



and I get the failure message. Is this the right way ..
Anyone please explain the correct way to achive it.

Answer

I have done something like below :--

My interface

    @Multipart
    @POST("your_path")
    Call<ProofResp> uploadFileWithPartMap(@PartMap Map<String, RequestBody> params,
    @Part("profile_pic\"; filename=\"image.jpeg\"") RequestBody file);

Now I am creating partmap like below

 HashMap<String, RequestBody> map = new HashMap<>();
 map.put("userId", toRequestBody(userId));

My RequestBody function is below :--

public RequestBody toRequestBody(String value) {
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
    return body;
}

Now the for the image part

RequestBody file=RequestBody.create(MediaType.parse("image/jpeg"),
createTempFile(your_bitmap));

Now the createTempFile funtion

private File createTempFile(Bitmap bitmap) {
        File file = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis()
                + "_image.jpeg");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();
//write the bytes in file

        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

Now send this file and map to your interface and you will get the response.Hope this above idea will help you to solve your problem.