0

I have to upload video file to Server using API, I am using Retrofit. I tried Multipart (by using different approaches) but failed.

I have to upload a video file, reference key as a string and url as a string (in body). In header, I have to upload token.

First I tried this:

Interace:

@Multipart
@POST(url)
Call<LivenessRequest> requestFun(@Header("Authorization") String token,
                                      @Part("reference") RequestBody referenceId,
                                      @Part("url") RequestBody url,
                                      @Part("file") RequestBody videoFile);

Making RequestBody Objects:

                RequestBody fileBody;
            RequestBody referenceBody;
            RequestBody urlBody;
            fileBody = RequestBody.create(okhttp3.MediaType.parse("video/*"), videoFile);
            referenceBody = RequestBody.create(okhttp3.MediaType.parse("text/plain"), String.valueOf(
                    "refernce_id_here"));
            urlBody = RequestBody.create(okhttp3.MediaType.parse("text/plain"), String.valueOf(
                    "www.google.com"));

calling API:

interface().requestFun(token,
                referenceBody, urlBody, videoFileBody).enqueue(new retrofit2.Callback<request>() {
            @Override
            public void onResponse(retrofit2.Call<request> call, Response<request> response) {
               
            }

            @Override
            public void onFailure(retrofit2.Call<request> call, Throwable t) {
            }
        });

I tried it with another approach that is:

Interface:

@Multipart
@POST(url)
Call<LivenessRequest> requestFun(@Header("Authorization") String token,
                                      @Body RequestBody body);

Making RequestBody Object:

RequestBody body = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",videoFile.getName(),
                            RequestBody.create(MediaType.parse("application/octet-stream"), videoFile))
                    .addFormDataPart("url","www.google.com")
                    .addFormDataPart("reference", reference)
                    .build();

API calling:

interface().requestFun(token, body).enqueue(new retrofit2.Callback<request>() {
            @Override
            public void onResponse(retrofit2.Call<request> call, Response<request> response) {
                
            }

            @Override
            public void onFailure(retrofit2.Call<request> call, Throwable t) {
            }
        });

Postman Screenshot of this api is attached: enter image description here

Faizan Ahmad
  • 352
  • 4
  • 20

0 Answers0