Spring Framework的图像文件处理的首选方法是什么?

时间:2017-06-29 06:37:29

标签: java spring image spring-mvc spring-rest

我有一个项目来创建Web服务,它将接受和操作图像作为使用Spring的响应。

我知道Spring的RESTful API的概念,专门用于XML和JSON响应,使用Jackson库与java对象的绑定,但我正在寻找相同类型的东西,但对于其他内容类型,如图像。< / p>

我有以下功能来上传和获取图像,但我不确定需要什么样的@RequestBody对象来绑定像BufferedImage这样的Image 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 ,但不太确定它是否对我的应用程序有用。

谢谢!

请让我知道你的想法。

1 个答案:

答案 0 :(得分:1)

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

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

来自the example

的代码

所以你只需通过POST发送文件&#34; multipart / form-data&#34;

要下载,您应该只写下图像文件字节

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

来自the example

的代码