Home » Android » java – Making a multipart post request with compressed jpeg byte array with spring for android

java – Making a multipart post request with compressed jpeg byte array with spring for android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’ve been using spring for android successfully in my android app to get/post data from/to the server. Now, I have to do a post request for a multipart form, but I’ve been unable to get it working the way I want.

Use case:
1. Pick a photo from the gallery
2. Load it to a bitmap using the file source
3. Compress the bitmap to a ByteArrayOutputStream
4. Pass the byte array ( ByteArrayOutputStream.toByteArray() ) to the server. (I need to send this as jpeg not application/octet-stream)

The server endpoint for upload photo accepts a MultipartFile with only the following Mime types ( Note, it does not accept MimeType: application/octet-stream ):

GIF("image/gif")
PNG("image/png", "image/x-png")
JPG("image/jpeg", "image/jpg", "image/pjpeg")
BMP("image/bmp")

I’ve tried using the sample code, but been unsuccessful so far.

With the following code I get the following error:
org.springframework.web.bind.MissingServletRequest ParameterException: Required MultipartFile parameter ‘file’ is not present

Help on this matter is greatly appreciated. Thanks and keep up the good work.

Here’s my code:

bitmap = BitmapFactory.decodeFile("/mnt/sdcard/DCIM/Camera/20130205_162546.jpg");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 60, bos);
byte[] data = bos.toByteArray();

// populate the data to post
MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
formData.add("caption", "Test Caption");
formData.add("file", data);

// The URL for making the POST request
final String url = "http://api.example.com/imageUpload?oauth_token=XXXXXX";

HttpHeaders requestHeaders = new HttpHeaders();

// Sending multipart/form-data
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

// Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate(true);

//    // Set a custom message converter that supports the application/json media type
//    final GsonHttpMessageConverter gsonMessageConverter = new GsonHttpMessageConverter();
//    gsonMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
//    final ByteArrayHttpMessageConverter byteArrayMessageConverter = new ByteArrayHttpMessageConverter();
//    byteArrayMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.IMAGE_JPEG));
//    final FormHttpMessageConverter formMessageConverter = new FormHttpMessageConverter();
//    formMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.IMAGE_JPEG));
//    restTemplate.getMessageConverters().addAll(Arrays.asList(gsonMessageConverter, byteArrayMessageConverter, formMessageConverter));

// Make the network request, posting the message, expecting a String in response from the server
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

// Return the response body to display to the user
Log.i(TAG, "**** response.body : " + response.getBody());
How to&Answers:

I’ve bumped into the same kind of problem and the solution was to override the org.springframework.core.io.Resource#getFileName() implementation.

In my case:

MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
// add values to map ... and when it comes to image:
Resource res = new ByteArrayResource(Utils.uriToByteArray(context, itemImage)) {
                    @Override
    public String getFilename() throws IllegalStateException {
        return imageFileName;
    }
};
HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.IMAGE_JPEG);
HttpEntity<Resource> imageEntity = new HttpEntity<Resource>(res, imageHeaders);
map.add("item[image]", imageEntity);

Where imageFilename is the file name. That will be later included as multipart header: Content-Disposition: form-data; name="your_image_form_item"; filename="20130520_142401.jpg"

I hope it helps!

Answer:

I too suffered this issue. Turned out that the body of my issue was on the server, server was not configured to handle/resolve multipart request.

Check out my detailed answer here. Hope it helps.