* Example code to return image with @ResponseBody

* Example code showing how to return images using @ResponseBody

* Example code showing how to return images using @ResponseBody
This commit is contained in:
Alexandre Lombard 2017-03-21 17:33:31 +01:00 committed by Grzegorz Piwowarek
parent eab4a5f8ca
commit bd237b2115
4 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,14 @@
package com.baeldung.produceimage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.produceimage")
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.produceimage.controller;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class DataProducerController {
@GetMapping("/get-text")
public @ResponseBody String getText() {
return "Hello world";
}
@GetMapping(value = "/get-image")
public @ResponseBody byte[] getImage() throws IOException {
final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
@GetMapping(value = "/get-image-with-media-type", produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] getImageWithMediaType() throws IOException {
final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
@GetMapping(value = "/get-file", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getFile() throws IOException {
final InputStream in = getClass().getResourceAsStream("/com/baeldung/produceimage/data.txt");
return IOUtils.toByteArray(in);
}
}

View File

@ -0,0 +1 @@
This is a sample file containing text data

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB