Spring 框架处理图像文件的首选方式是什么?

What is the preferred way of Image file handling for Spring Framework?

我有一个项目要创建 Web 服务,使用 Spring 接受和处理图像作为响应。

我知道 Spring 的 RESTful API 的概念,专门用于 XML 和 JSON 响应,使用 Jackson 与 java 对象的绑定图书馆,但我一直在寻找同样的东西,但对于图像等其他内容类型。

我有以下上传和获取图像的功能,但我不确定需要什么 @RequestBody 对象来绑定像 BufferedImage 这样的图像 POJO,以便我将来可以操作它。

// 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.
}

有了这个,我一直在寻找一种更好的方法来处理 Spring 的图像文件,并提供更简洁的解释。

我也阅读了有关 BufferedImageHttpMessageConverter 的内容,但不太确定它是否对我的应用程序有用。

谢谢!

请告诉我你的想法。

上传所需的只是普通的上传文件。

@PostMapping("/upload") // //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {

代码来自the example

所以您只需通过 POST 和 "multipart/form-data"

发送文件

对于下载你应该只写图像文件字节

@GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {
    InputStream in = getClass()
      .getResourceAsStream("/com/baeldung/produceimage/image.jpg");
    return IOUtils.toByteArray(in);
}

代码来自the example