java - 通过spring Controller 从服务器返回图片

标签 java spring spring-mvc

在我的 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);
}  

愿这对您有帮助。

引用:
Image Download with Spring MVC .

关于java - 通过spring Controller 从服务器返回图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24758239/

相关文章:

java - 如何匹配具有()或(任何字符)java的字符串

spring - 使用 Maven 构建 Spring 项目时,Netbeans 包括 XML 和属性

java - 如何使用 Spring boot 应用程序连接具有不同 Ip 和凭据的 2 个 mySql 数据库

java - Spring Data JPA 中的自定义(原始)查询

java - 如何模拟带注释的 EJB?

javax.persistence.RollbackException : Error while committing the transaction] with root cause java. lang.StackOverflowError: 空

最新 JRE (7.55+) 上的 Java Applet 奇怪的性能行为

java - Bean 验证 @Positive 指令不适用于 Integer @PathVariable

java - 如何使用Jsp JSTL显示Spring模型?

java - com.fasterxml.jackson.databind.ser.BeanSerializer.serialize Spring JPA