2017-04-21 20 views
0

我正在构建一个使用spring启动和mongodb的blogging的web应用程序。我尝试使用gridFS存储和使用输入流来存储数据。但我不能回的图像作为模型attribute.It是我的控制器类如何在春季4中存储和返回图像作为模型属性

@RestController 
public class HomeController { 

@Autowired 
GridFsTemplate gridFsTemplate; 

@RequestMapping(value = "/home", method = RequestMethod.GET) 
@ResponseBody 
public ResponseEntity<InputStreamResource> getImage() { 
    GridFSDBFile gridFsFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("metadata.user").is("5")));; 
    InputStream inputStream = gridFsFile.getInputStream(); 
    System.out.println("done"); 
    return ResponseEntity.ok() 
      .contentLength(gridFsFile.getLength()) 
      .contentType(MediaType.parseMediaType(gridFsFile.getContentType())) 
      .body(new InputStreamResource(gridFsFile.getInputStream())); 
} 
} 

,这是我的看法

<html xmlns:th="http://www.thymeleaf.org"> 
<head> 
</head> 
<body> 
<img th:src="@{/home}" /> 
</body> 
</html> 
+0

欢迎SO。你应该发布一些你的代码尝试。否则,你会得到一堆倒票和评论,说这不是一个代码写作服务。 – BWMustang13

+0

我添加了我的代码 –

+0

只是为了清楚起见 - 你是**不是**在代码中的任何位置返回一个图像作为模型属性 - 你正在做的是将图像作为响应主体返回到'/ home'端点。当你在浏览器中打开'/ home'端点时会发生什么?图像显示出来了吗? – vtosh

回答

0

你可以得到图像的字节[],然后可以这样写字节数组以响应对象。现在将这个方法映射到一些url。代码会是这样的 -

@RequestMapping(value="/imgPath") 
public void imgResponse(HttpServletResponse response){ 
ServletOutputStream stream = response.getOutputStream(); 
    /* get byte array and assign it to the variable dataa */ 
    stream.write(data); 
    stream.flush(); 
} 

现在你可以在JSP中提供这个形象像 -

<img src="./imgPath""/>