在我的 spring Controller 中,我添加了这两种方法,从我的 View 上传和下载图片:
@RequestMapping(value="picture/{theString}", method=RequestMethod.GET)
public byte[] getPicture(@PathVariable("theString") String theString) {
return serv.download_picture(theString);
}
@RequestMapping(value="upload", method=RequestMethod.POST)
public boolean setPicture(@ModelAttribute("object") E object, BindingResult result, @RequestParam("file") MultipartFile file) {
return serv.upload_picture(object, file);
}
setPicture(在服务类中具有等效的 upload_picture)已经实现,但我需要一些关于如何实现 download_picture 的想法,以便我能够执行类似的操作:
<img src="<c:url value="<<Entity>>/picture/<<id>>"/>">
任何人都可以指出这样做的方向吗?
PS:如果可能的话,我想在我的服务类中为我的方法 download_picture 使用此声明:
public byte[] download_picture(String path) {
return null;
}
其中路径是我想要下载图片的实体的 ID。
PS.:图片存放在/src/main/resources
文件夹中在我的 spring/maven 应用程序中。该路径中的完整 URL 类似于 <<entity>>/<<id>>/foto.jpeg
最佳答案
在 Spring 3.1 或更高版本中,您可以在 @RequestMapping
注释中指定 products
。
下面是示例。
@ResponseBody
@RequestMapping("picture/{theString}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto(@PathVariable("theString") String theString) throws IOException
{
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg"); //
//Here you may write above code in service class to read file from path "/src/main/resources" as stream and return it to controller class.
return IOUtils.toByteArray(in);
}
愿这对您有帮助。
关于java - 通过spring Controller 从服务器返回图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24758239/