0

I am new to spring boot and android development. I'm trying to set up and android app (using retrofit and okhttp3) which will upload images to my server.

Server code:

@RestController
public class ImageController {
    @RequestMapping(value = "/uploadImage", method =RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String greeting(@RequestPart(value="desc") RequestBody desc, @RequestPart(value="img") MultipartBody.Part image) {
        System.out.println("Works");
        return "Works";
    }
}

Android code:

MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", imageFile.getName(), requestBody);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), imageFile.getName());


@Multipart
@POST("/uploadImage")
Observable<retrofit2.Response<String>> uploadPhoto(@Part("desc") RequestBody desc,@Part MultipartBody.Part image);

Error:

{"timestamp":1519756785858,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'text/plain;charset=utf-8' not supported","path":"/uploadImage"}

Can someone tell me what I'm doing wrong????

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
bdeane
  • 52
  • 9
  • Welcome to Stackoverflow. Next time please format your code properly, so that it is better readable for others. This time I did it for you. – Thomas Fritsch Feb 27 '18 at 19:24

1 Answers1

0

EDIT:

Try this...

@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public String greeting(@RequestParam("file") MultipartFile file) {
    try {
        byte[] bytes = file.getBytes();

        //to save file, if it is your case
        Path path = Paths.get("/" + file.getOriginalFilename());
        Files.write(path, bytes);

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

}

I didn't understand very well your Android code, but I'd try something like this:

HttpPost httpPost = new HttpPost("http://url");

httpPost.setEntity(new FileEntity(new File("filePath"), "application/octet-stream"));

HttpResponse response = httpClient.execute(httpPost);
Leonardo
  • 1,263
  • 7
  • 20
  • 51
  • but then i get the error {"timestamp":1519844515434,"status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'multipart/form-data;boundary=ad983eba-75d8-49cd-bbdc-e48f1ef44814' not supported","path":"/uploadImage"} – bdeane Feb 28 '18 at 19:02
  • @bdeane I have editted the answer. Check if it will help you. – Leonardo Feb 28 '18 at 19:30