【问题标题】:Spring:Writing image from GridFS to jsp viewSpring:将图像从 GridFS 写入 jsp 视图
【发布时间】:2013-12-26 09:48:20
【问题描述】:

我正在使用 GridFS 来存储图像。现在我想直接将存储的图像写入弹簧视图页面我尝试了很多,但没有成功。我可以使用

将图像写入本地系统
gfs.writeTo("my location of local directory");

但是如何在 spring 中将相同的图像写入 JSP 视图?任何帮助表示赞赏。

【问题讨论】:

    标签: spring spring-mvc gridfs spring-data-mongodb


    【解决方案1】:

    这对我有用

    服务方式:

    @Override
    public void serveImage(String imageId , HttpServletResponse response ) {
        InputStream is = null;  
    
        ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoDBConfiguration.class);
        GridFsOperations gridOperations = (GridFsOperations) ctx.getBean("yourBeanName");
    
        List<GridFSDBFile> result = gridOperations.find(new Query().addCriteria(Criteria.where("_id").is(imageId)));
    
        for (GridFSDBFile file : result) {
            try {
                response.setHeader("Content-Disposition", "inline; filename=image.jpg");
                response.setContentType("image/jpg");
                response.setContentLengthLong(file.getLength());
    
                is = file.getInputStream();
                IOUtils.copy(is, response.getOutputStream());
    
                response.flushBuffer();
    
            } catch (java.nio.file.NoSuchFileException e) {
                response.setStatus(HttpStatus.NOT_FOUND.value());
            } catch (Exception e) {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        }
    }
    

    HTML代码:

    <image>
        <source th:src="@{/get/${imageId}}" type="image/jpg">
    </image>
    

    控制器类:

    @RequestMapping(value = "/get/{imageId}", method = RequestMethod.GET)
    public void handleFileDownload(@PathVariable String imageId, HttpServletResponse response) {
        try {
            vaskService.serveImage(imageId,  response);
    
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2015-12-07
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 2015-07-13
      • 2014-12-05
      相关资源
      最近更新 更多