简体   繁体   中英

Uploading image to a Spring-Boot web server from android

I am using retrofit 2 library to send image from android device to a server which runs on Spring - Boot. I want to simply send an image to see, if all is ok, so i perform this simple type of request:

On server side my controller looks like this:

 @PostMapping(value = "/updatePhoto" )
public String updateUserPhoto(@RequestPart(name = "img") MultipartFile img) {
    {
        System.out.println("Request  update photo "+ img.getOriginalFilename());
        return "OK";
    }

This is my request

@POST("/updatePhoto")
@Multipart
Call<String> updateUserPhoto(@Part MultipartBody.Part img);

This is how i perform it:

 File file = new File(mediaPath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);


        System.err.println(filename+"  " + fileToUpload);
        MainAplication.getServerRequests().updateUserPhoto(fileToUpload)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        if(response.body()!=null){
                            System.err.println(response.body());
                        }else{
                            System.err.println("RESPONSE BODY NULL");
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        System.err.println("UPDATE PHOTO FAIL " +t.getMessage());
                    }
                });

But every time i try to send an image, my server throws an exception :

org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'img' is not present

And can t understand where i m doing wrong, i had tried a lot, but a can`t solve this problem. Any ideas what must i improve ?

Try this "img" instead of "file"

 RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
 MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("img", file.getName(), requestBody);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM