1

On client side I crop the image to the width and height 250px. I send the image as base64. The result of cropper is always base64 and there are some issues in case I want to make from this multi-part.

I wonder about the performance for sending the images as just String value to the controller and managing this, in case that the someone would upload the image directly or any situation of direct use the api.

Is it correct way of uploading the image, manage and validate ?

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<?> upload(@RequestParam("imageValue") String imageValue, HttpServletRequest request) {
    try {
        String splitter = ";base64,";

        String[] splitted = imageValue.split(splitter);

        if (splitted.length != 2)
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

        byte[] imageByte = Base64.decodeBase64(splitted[1]);

        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        BufferedImage image = ImageIO.read(bis);

        if (image == null || image.getHeight() > 250 || image.getWidth() > 250)
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

        FooImageData fooImageData = new FooImageData ();
        fooImageData.setBase64(imageByte);
        fooImageData.setMimeType(splitted[0] + splitter);

        fooImageDataService.save(fooImageData);
        bis.close();
        return new ResponseEntity<>(HttpStatus.OK);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

}
kxyz
  • 802
  • 1
  • 9
  • 32

1 Answers1

0

The Base64 encoding uses 4 bytes for every 3 bytes worth of binary data. This is probably fine - it's only 33% more data.

I'm more concerned about passing this data as a request parameter, instead of in the body of the request. As you can see in this question, there are sometimes limits on how much data servers and clients can handle in a single request parameter. I'd consider using Spring's @RequestBody instead.

Andrew Rueckert
  • 4,858
  • 1
  • 33
  • 44