Reputation: 447
I am trying to understand how to get an image from an Java Spring
back-end to show in a small React
app.
In React
, I am trying to set an img src
to the image-data
using this code:
const [image, setImage] = useState("");
const onClickHandler = async () => {
const result = await fetch("http://localhost:8080/gallery/test", {
mode: "no-cors", // 'cors' by default
});
const blob = await result.blob()
const url = await URL.createObjectURL(blob);
setImage(url)
console.log(url)
}
But console.log
shows this info:
blob:http://localhost:3000/620ccbb6-31e5-4a2c-9a61-540beba10d8e
Controller
code:
@Controller
@RequestMapping("/")
public class GalleryController {
protected final GalleryService galleryService;
@Inject
public GalleryController(GalleryService galleryService) {
this.galleryService = galleryService;
}
@GetMapping(value = "gallery/test")
public @ResponseBody byte[] getImage() throws IOException {
return IOUtils.toByteArray(getClass()
.getResourceAsStream("/gallery/test/test.jpg"));
}
}
And if I open http://localhost:8080/gallery/test/
, I get this:
Upvotes: 1
Views: 2561
Reputation: 1568
You should tell to the browser that content type of the byte array will be jpg image.
You need to change @GetMapping annotation to this:
@GetMapping(value = "gallery/test", produces = MediaType.IMAGE_JPEG_VALUE)
MediaType from package "import org.springframework.http.MediaType;" tells to the browser that there will be image in response from controller.
Upvotes: 3