Access files that are outside webapp (Tomcat V6 an

2020-07-30 03:13发布

问题:

I am giving option to upload images and the Images are being upload to opt/uploads/contactImages which in the case of windows is C:/opt/uploads/contactImages

I want to display Images in my JSP. For which I tried to configure my tomcat by adding the following tag under Host tag.

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

But when I try to access

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

I get 404 Error. Where I am going wrong?

Update

Servlet web.xml file

<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>

回答1:

A Servlet or a resource handler can't just serve files from the file system directly. You need to write your own @Controller handler methods. For example

@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;
    }
}

With the ResponseEntity class you can also set different response headers and status codes.

You can now access the above at

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

I don't think the above will work for files in nested directories.


Note that the docBase attribute in

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

is incorrect. The docBase attribute specifies

The Document Base (also known as the Context Root) directory for this web application, or the pathname to the web application archive file (if this web application is being executed directly from the WAR file). You may specify an absolute pathname for this directory or WAR file, or a pathname that is relative to the appBase directory of the owning Host.

So it has to point to your web application, not a random directory where you store files.



标签: spring tomcat