访问 webapp 外部的文件(Tomcat V6 和 Spring)

2024-05-27

我提供上传图像的选项,并且图像正在上传到 opt/uploads/contactImages,在 Windows 中为 C:/opt/uploads/contactImages

我想在我的 JSP 中显示图像。为此,我尝试通过在主机标签下添加以下标签来配置我的tomcat。

<Context docBase="/opt/uploads/contactImages/" path="/images" />

但是当我尝试访问时

http://localhost:8080/images/file.png 

我收到 404 错误。我哪里错了?

Update

Servlet web.xml 文件

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring Web MVC Application</display-name>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

A Servlet或者资源处理程序不能直接从文件系统提供文件。你需要自己写@Controller处理程序方法。例如

@Controller
public class ImagesController {

    public static final String BASE_PATH = "/opt/uploads/contactImages";

    @RequestMapping(value = "/{fileName}" , method = RequestMethod.GET) 
    public ResponseEntity<FileSystemResource> getFile(@PathVariable("fileName") String fileName) {
        FileSystemResource resource = new FileSystemResource(new File(BASE_PATH, fileName));
        ResponseEntity<FileSystemResource> responseEntity = new ResponseEntity<>(resource, HttpStatus.OK);
        return responseEntity;
    }
}

随着ResponseEntity http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/http/ResponseEntity.html类中你还可以设置不同的响应头和状态码。

您现在可以访问上述内容

http://localhost:8080/images/file.png 

我认为上述内容不适用于嵌套目录中的文件。


请注意,docBase属性在

<Context docBase="/opt/uploads/contactImages/" path="/images" />

是不正确的。这docBase http://tomcat.apache.org/tomcat-7.0-doc/config/context.html属性指定

文档库(也称为上下文根)目录 Web 应用程序,或 Web 应用程序存档文件的路径名 (如果此 Web 应用程序直接从 WAR 执行 文件)。您可以为此目录或 WAR 指定绝对路径名 文件,或相对于 appBase 目录的路径名 拥有主机。

因此它必须指向您的 Web 应用程序,而不是存储文件的随机目录。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

访问 webapp 外部的文件(Tomcat V6 和 Spring) 的相关文章

随机推荐