Reputation: 480
I have a project to create web services that would accept and manipulate images as a response using Spring.
I know the concept of RESTful APIs for Spring specifically for XML and JSON responses, the bindings with the java objects using the Jackson library, but I was looking for the same kind of thing but for other content-types like images.
I have the below functionality to upload and fetch the image but I am not sure on what @RequestBody object is needed to bind Image POJOs like BufferedImage so that I could manipulate it in the future.
// Upload the image from a browser through AJAX with URI "../upload"
@RequestMapping(value="/upload", method=RequestMethod.POST, consumes={"image/png", "image/jpeg"})
protected void upload(@RequestBody ???){
// upload the image in a webserver as an Image POJO to make some image manipulation in the future.
}
// Fetches the image from a webserver through GET request with URI "../fetch/{image}"
@RequestMapping(value="/fetch/{image}", method=RequestMethod.GET)
protected @ResponseBody String fetch(@PathVariable("image") String imageName){
// fetch image from a webserver as a String with the path of the image location to be display by img html tag.
}
With this, I was looking for a more preferred way of doing the image file handling for Spring with a more concise explanation.
I have also read about BufferedImageHttpMessageConverter but not quite sure if it is useful to my application.
Thank you!
Please let me know your thoughts.
Upvotes: 1
Views: 1675
Reputation: 57381
All you need for uploading is usual upload file.
@PostMapping("/upload") // //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
The code from the example
So you just send the file by POST with "multipart/form-data"
For downloading you should just write the image file bytes
@GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
The code from the example
Upvotes: 2