【问题标题】:How to display image in jsp in a spring application如何在spring应用程序中的jsp中显示图像
【发布时间】:2014-10-29 11:59:28
【问题描述】:

我的应用程序的用户上传了某些图像,并且只能由他们访问。我怎样才能将它们显示为缩略图或其他方式。我将图像存储在文件系统(webapp 外部)中,并且只将它们的路径存储在数据库中。

我发现的一个选项是配置 tomcat 以通过 server.xml 中的以下更改来公开该目录。

<Context path="/images" docBase="/home/app/basedir" />     

然后通过

访问图片
localhost:8080/context/images/b1sd2e09102.jpg 

等等。 (我是使用UUID生成随机图片名称,以免被猜到)

但是,这对我来说不是一个理想的解决方案,因为网址(如果其他用户知道的话)仍然是公开的。 目前我可以通过在我的 spring 控制器中下载它们:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(Model model, @RequestParam("id") String key, HttpServletResponse response) throws Exception {
    //get item from db first based on key
    Item item = dbservice.get(key);
    InputStream is = new FileInputStream(item.getPath());     
    response.setHeader("Content-Disposition", "attachment; filename=" + item.getFileName());
    IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();
    ....
}

有没有办法在浏览器上呈现这些图像?

【问题讨论】:

    标签: jsp spring-mvc spring-security


    【解决方案1】:

    您离完整的解决方案不远了。我目前使用你的例子附近的东西。我只需添加一个Content-Length 标头并使用我在上传文件时存储在数据库中的Image/xxx 内容类型。如果不存在,我使用原始名称的扩展名。

    所以它可能看起来像:

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(Model model, @RequestParam("id") String key, HttpServletResponse response) throws Exception {
        //get item from db first based on key
        Item item = dbservice.get(key);
        InputStream is = new FileInputStream(item.getPath());
        String type = item.getFileType();
        if ((type == null) || (type.isEmpty())) {
            String name = item.getFileName();
            if (name.length > 2) {
                int i = name.substring(0, name.length() - 1).lastIndexOf(".");
                if (i > 0) {
                    type = "Image/" + name.substr(i + 1);
                }
            }
        }
        if ((type == null) || (type.isEmpty())) {
            tyoe = "application/octet-stream";
        }
        response.setHeader("Content-Type", type);
        int l = item.getFileLength();
        if (l > 0) {
            response.setContentLength((int) resource.contentLength());
        }
        response.setStatus(HttpServletResponse.SC_OK);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
        ....
    }
    

    现在,您只需在希望浏览器插入图片的位置放置一个图片标签

    <img src="/appContext/dowload?id=key"/>
    

    但是你也应该把尺寸和类型放在图片标签中。

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2014-09-19
      • 2012-06-28
      相关资源
      最近更新 更多