我有一个项目来创建 Web 服务,该服务将使用 Spring 接受和操作图像作为响应。
我知道 Spring 的 RESTful API 的概念,专门用于 XML 和 JSON 响应,以及使用 Jackson 库与 java 对象的绑定(bind),但我一直在寻找相同类型的东西,但适用于图像等其他内容类型。
我有以下功能来上传和获取图像,但我不确定需要什么 @RequestBody 对象来绑定(bind)像 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
因此,您只需使用“multipart/form-data”通过 POST 发送文件
要下载,您只需写入图像文件字节
@GetMapping(value = "/image")
public @ResponseBody byte[] getImage() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/com/baeldung/produceimage/image.jpg");
return IOUtils.toByteArray(in);
}
代码来自the example
关于java - Spring 框架处理图像文件的首选方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44817971/