How to send requestparam with Multipart file using retrofit?

I have this endpoint in spring boot.

    @PostMapping("/uploadPhoto")
    public String uploadPhoto(@RequestParam String email, @RequestPart(name = "img") MultipartFile file) {
        studentService.updateImageLink(email, file);
        return "OK";
    }

And Service endpoint in retrofit

    @POST("uploadPhoto")
    @Multipart
    suspend fun uploadPhoto(@Part("email") email: String, @Part img: MultipartBody.Part): String

Here how I am sending my file

val file = File(getPath(selectedImage!!));
            val requestBody = RequestBody.create(MediaType.parse("*/*"), file);
            val fileToUpload = MultipartBody.Part.createFormData("img", file.name, requestBody);
            viewModel.uploadPhoto("[email protected]", fileToUpload);

I am getting retrofit2.HttpException: HTTP 400 . Is this problem form server-side or client-side?

Upvotes: 0

Views: 1295

Answers (1)

alierdogan7
alierdogan7

Reputation: 840

You should send your primitive type arguments as a RequestBody instead of String.

@Multipart
@POST("uploadPhoto")
Call<Void> uploadPhoto(@Part("email") RequestBody email, 
                       @Part MultipartBody.Part image);

and in your request method you should insert your parameters like the following:

public void uploadProfileImage(String email, File imageFile) {
    RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);

    MultipartBody.Part imageBody = MultipartBody.Part.createFormData("image", imageFile.getName(), requestFile);

    RequestBody emailBody = RequestBody.create(MediaType.parse("multipart/form-data"), email);

    getRetrofitClient().uploadPhoto(emailBody, imageBody);
}

Upvotes: 5

Related Questions