Skip to content Skip to sidebar Skip to footer

Retrofit2: Upload An Image With Some Form Data-android

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)

Solution 1:

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 :--

publicRequestBodytoRequestBody(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) {
        Filefile=newFile(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis()
                + "_image.jpeg");
        ByteArrayOutputStreambos=newByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0/*ignored for PNG*/, bos);
        byte[] bitmapdata = bos.toByteArray();
//write the bytes in filetry {
            FileOutputStreamfos=newFileOutputStream(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.

Post a Comment for "Retrofit2: Upload An Image With Some Form Data-android"