S Haque
S Haque

Reputation: 7271

Upload image with retrofit 2

Interface:

@Multipart
@POST("emp/passportupload")
Single<ApiResponse> uploadPassportImage(@Query("passportnumber") String passportNumber, @Part MultipartBody.Part file);

Calling api:

File file = new File(model.getImage().getPath());
if (!file.exists()) return null;
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData(ApiConstant.PICTURE_UPLOAD_PARAM, file.getName(), requestBody);

dataService.uploadPassportImage(map, filePart)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread());

I am using this method to upload image to the server but server can't validate it as an image, hence giving me a response like

"Provided File Is Not A Valid Picture. Please Provide A PNG/JPG File"

But, I have uploaded the same image file through postman and it was successful. Here is the request: (N.B: passportnumber is a params, not a form data) enter image description here

Upvotes: 0

Views: 5296

Answers (4)

Lalit Jadav
Lalit Jadav

Reputation: 1427

@Multipart
@POST("changeCompanyLogo")
Call<ChangeLogoResponse> changeCompanyLogo(@Part MultipartBody.Part image, @Part("JSON") RequestBody name);

In service write this code

ChangeLogoAPI service = ServiceHandler.getClient().create(ChangeLogoAPI.class);
        File file = new File(intent.getStringExtra("imagePath"));
        RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("companyLogo", file.getName(), reqFile);
        RequestBody name = RequestBody.create(MediaType.parse("text/plain"), new Gson().toJson(new ChangeLogoParams()));
        Call<ChangeLogoResponse> call = service.changeCompanyLogo(body, name);
        call.enqueue(new Callback<ChangeLogoResponse>() {
            @Override
            public void onResponse(Call<ChangeLogoResponse> call, Response<ChangeLogoResponse> response) {
                Log.d(TAG, "response: " + response.isSuccessful());


            }

            @Override
            public void onFailure(Call<ChangeLogoResponse> call, Throwable t) {

            }
        });

Upvotes: 3

Hardik Mehta
Hardik Mehta

Reputation: 887

use this awesome library : [Easily upload files (FTP / Multipart / Binary) in the background with progress indication notification] https://github.com/gotev/android-upload-service/wiki/Setup it will do the rest of work for you.

Upvotes: 0

Aashutosh Kumar
Aashutosh Kumar

Reputation: 183

@POST("{path}")
Call<Void> uploadFile(@Header("Content-Type") String type,  @Body RequestBody photo,  @Path("path") String path);


    File file = new File("YOUR_FILE_URI");

    String filename = file.getName();
    String fileExtension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
    final String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);


    InputStream in = null;
    RequestBody requestBody = null;
    try {
        in = new FileInputStream(file);
        byte[] buf;
        buf = new byte[in.available()];
        while (in.read(buf) != -1);
        requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), buf);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
    Call<Void> call = getResponse.uploadFile(type, requestBody , posturl);

Upvotes: 1

Anil
Anil

Reputation: 1614

U can try like this u need to set map parameter as a multipart look at the below example here I am passing both userId and image

RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);

MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
MultipartBody.Part id = MultipartBody.Part.createFormData("userId", userId);
Call<ProfilePicUpdateResponse> call = apiService.updateProfilePic(id,fileToUpload);

Upvotes: 0

Related Questions