Nabat Farsi
Nabat Farsi

Reputation: 992

Posting and image using Okhttp to Django Rest Frame work Back end

I have a back end that I am able to upload a file to it by the following request in Pyhton:

data = {
    "prop_post": 35
}
headers = {
    # "Content-Type": "application/json",
    "Authorization": "JWT " + t1,
}
if img_path is not None:
    with open(img_path, 'rb') as image:
        file_data = {
            'photo': image
        }
        r = requests.post(POSTS_ENDPOINT, data=data,files=file_data, headers=headers)

that is my development environment. Now in production I am going to use Android as client to upload image. I am using Okhttp3. Here is the code that I am using to upload an image:

final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");
                            String file2 = utils.getRealPathFromURI2(obj.getPhotos_uri()[0], context);
                            File file = new File(file2);
                            RequestBody req = new MultipartBody.Builder()
                                    .setType(MultipartBody.FORM)
                                    .addFormDataPart("prop-post", Integer.toString(id))
                                    .addFormDataPart("photo", "IMG-20190705-WA0002.jpg",
//                                            RequestBody.create(MEDIA_TYPE_PNG, file.getAbsolutePath())).build();
                                            RequestBody.create(MEDIA_TYPE_PNG, file)).build();

                            Request request = new Request.Builder()
                                    .url(root + "images/")
                                    .addHeader("Authorization", header)
                                    .post(req)
                                    .build();

                            OkHttpClient client = new OkHttpClient();
                            Response response2 = client.newCall(request).execute();

This request doesn't go through with 400 (Bad request) response. My file absolute location in Android is : /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20190705-WA0002.jpg

I appreciate if some one can tell me what I am doing wrong. Thanks in advance

Upvotes: 1

Views: 348

Answers (1)

Nabat Farsi
Nabat Farsi

Reputation: 992

I ended up using retrofit: added these dependencies in gradle:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

then defined the following interface:

public interface ImageAPI {
    @Multipart
    @POST("images/")
    Call<ResponseBody> createPost( @Part MultipartBody.Part file, @Part("prop_post") RequestBody requestBody);
}

then my post call looks like this:

OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request.Builder newRequest = request.newBuilder().header("Authorization", "mytoken");
                        return chain.proceed(newRequest.build());
                    }
                });
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(rootUrl)
                .client(okHttpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();


        ImageAPI imageAPI = retrofit.create(ImageAPI.class);


        String image_path = imagepath;//sets when browsing image
        File file = new File(image_path);

        RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("photo", file.getName(), fileReqBody);


        RequestBody id= RequestBody.create(MediaType.parse("text/plain"), "68");



        Call<ResponseBody> call = imageAPI.createPost(part, id);
        try {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    Log.d("tag", "onResponse: " + response.message().toString());
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.d("tag", "onResponse: " + t.getMessage());

                }
            });
        } catch (Exception e) {
            Log.d("tag", "onCreate: " + e.getMessage());
        }

Upvotes: 1

Related Questions