【问题标题】:How to call images from file system?如何从文件系统调用图像?
【发布时间】:2014-09-25 16:06:29
【问题描述】:

我正在使用 eclipse WTP 在 Ubuntu 操作系统上开发 Web 应用程序,这些应用程序部署在 tomcat 服务器上。我想在网络应用程序的文件系统中使用图像(显示它们)。我怎样才能有效地做到这一点?是通过使用上下文路径到驱动器上的位置吗?还是通过使用流媒体加载它们(或类似的东西)?另外,我在 WTP 项目中找不到任何 web.xml 或 server.xml 文件(因为新版本甚至不需要它们)。

改写:我想在我的网络应用程序中使用来自文件系统的图像(静态内容)。在前端使用 JSTL。

编辑:

如果网络应用程序是xyz,那么它的位置是:/home/webaapp/xyz/.....,图像在/home/akshay/images/.......

我想从网络应用程序访问一个很远的文件夹(在同一个硬盘上)

【问题讨论】:

  • 使用上下文路径并确保您已移动 webapp 文件夹中的所有图像,并且 Web 应用程序能够访问这些图像。
  • 你的前端技术是什么?
  • 我已经在为 css/js 使用 WebContent 文件夹,但是,我想要使用的图像数量巨大并且经常被更改(删除、添加)。我看不到如何在 tomcat 部署文件 .war 中做到这一点
  • 更新问题。它的 jSTL

标签: java jsp tomcat servlets jstl


【解决方案1】:

您可以使用Tomcat Default Servlet 提供静态资源。

web.xml:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

最好使用c:url 并在值中使用前缀/ 以使url 相对于上下文路径。

<img id="logo" src="<c:url value='/resources/images/logo.png'/>" />

动态项目结构:

WebContent
         |
         |__resources
         |          |
         |          |__images
         |                   |
         |                   |__logo.png
         |
         |__WEB-INF
                  |
                  |__web.xml

编辑

由于图像不是战争的一部分,因此您可以尝试使用 Servlet。只需将路径存储在属性文件中的某处或将其作为 VM 参数传递或使其保持不变。

JSP:

<img src="${pageContext.servletContext.contextPath}/servletURL?name=logo.png"/>

小服务程序:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String imageName=request.getParameter("name")
    String path = "absolute path of the image directory"+imageName;
    BufferedInputStream inputStream = null;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(new File(path)));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024 * 2];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, bytesRead);
        }
        outputStream.flush();
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

如果您使用的是 Java 7,请使用 The try-with-resources Statement 处理资源。

【讨论】:

  • 但图片与网络应用的目录不同。如果网络应用程序是 xyz,那么它的位置是:/home/webaapp/xyz/..... 并且图像在 /home/akshay/images/....... 我想访问一个很远的文件夹(在相同的硬盘驱动器)来自网络应用程序。
  • OK 然后将路径存储在属性中的某处或将其作为系统环境变量传递。向上阅读应用程序上下文中的路径。让我更新我的帖子。
  • 帖子也更新了代码。试试看,让我知道结果。
猜你喜欢
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
  • 2016-03-14
  • 2018-12-24
  • 2017-12-12
相关资源
最近更新 更多