Search code examples
androidspringandroid-annotations

Sending images with AndroidAnnotations RestService


What is the best way to send a file using the RestService? I have an image that I have to send to the server.

The API expects the following POST data:

image -> image I want to send
description -> text
title -> text

Can I just send an object with the needed values to achieve this or do I have to do it another way?

class NewImage {
    private Bitmap image;
    private String description;
    private String title;
}

Solution

  • You should use a multipart POST request:

    Client:

    @Rest(rootUrl = "your_url", converters = FormHttpMessageConverter.class)
    public interface UploadClient extends RestClientHeaders {
        @Post("/Image/{id}")
        @RequiresHeader(HttpHeaders.CONTENT_TYPE)  
        String uploadImage(int id, MultiValueMap<String, Object> data);     
    }
    

    Usage:

    MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
    
    FileSystemResource image = new FileSystemResource("path_to_image");
    String description = "description";
    String title = "title";
    
    data.put("image", image);
    data.put("description", description);
    data.put("title", title);
    
    client.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
    
    client.uploadImage(1, data);
    

    I know this has some boilerplate, but it will be improved in the near future.

    Reflect for the question in the comment:

    You can create a class:

    class ObjectSupportingFormHttpMessageConverter extends FormHttpMessageConverter {
        public ObjectSupportingFormHttpMessageConverter() {
            addPartConverter(new ObjectToStringHttpMessageConverter(new DefaultConversionService()));
        }
    }
    

    Then use it as a converter. This will convert your objects to text/plain parts. However, maybe it is better to serialize this complex structure into JSON instead of sending it in the multipart post.