Vladislav  Solopov
Vladislav Solopov

Reputation: 137

How to display an image using byte [] Java? Spring MVC

Reading various tutorials I come across the possibility of displaying an image, returning an array of bytes. I need to display the resulting image, but in return I get a set of byte-numbers on the page. What do I need to change / add to work?

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody byte[] handleFileUpload(@RequestParam("file") MultipartFile file) {
     try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //find the file extension
            if (!extension.equals("jpg") && !extension.equals("jpeg") &&
                    !extension.equals("bmp") && !extension.equals("png")) throw new Exception();

            InputStream in = new ByteArrayInputStream(file.getBytes());
            BufferedImage bufferedImage= ImageIO.read(in);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, extension, os);
            InputStream is = new ByteArrayInputStream(os.toByteArray());
           return os.toByteArray();
        } catch (Exception e) {
        }
    return new byte[0];
}

Do not pay attention to error handling. deliberately removed body treatments

Upvotes: 1

Views: 977

Answers (1)

Vladislav  Solopov
Vladislav Solopov

Reputation: 137

I added to the body @RequestMappting produces = {"image/jpg, image/jpeg, image/png, image/bmp"} and it all worked

Upvotes: 1

Related Questions