访问 Webcontent 文件夹外的文件

Access files outside the Webcontent folder

我在webcontent外做了一个文件夹用来保存用户上传的图片。最初我试图通过在 "src" 标记中传递位置来直接访问这些文件,但无法获取它。经过研究,我发现我必须使用标签内的 "conf/server.xml" 文件设置路径。虽然我已经做了所有这些更改,但我无法访问该文件。

1)我的 Tomcat 安装在 E:\my work\Tomcat

2) 我的 webroot 位于 E:\my work\Project

3)图片文件夹在 E:\my work\images

我在 "conf\server.xml" 中设置的路径是

    <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true"
        xmlValidation="false" xmlNamespaceAware="false">
   <Context docBase="/my work/images/" path="/images"  />
   </Host>

但是当我尝试使用以下 url

访问文件时
           http://localhost:8080/images/paper.jpg

我无法获取它并收到 "HTTP Status 404" 和请求资源未找到错误。

请帮助我,当用户请求特定图像时,我正在使用 Blob 字段存储图像并将图像存储在此文件夹中。我不想使用特定的 servlet 将图像写入浏览器,而是希望直接访问用户。

请帮我解决这个问题。 谢谢 关注

根据我的理解,您的项目应该在 tomcat webapps 文件夹中并且图像应该像

webapps/YourProject/resources/images/something.jpg

webapps/YourProject/WEB-Content/images/something.jpg

根据我的经验,我认为您不必在任何 xml 中设置路径。只需直接访问图像,您就可以访问它。容器限制对 WEB-INF 文件夹中的任何内容的访问。

对此的解决方案是编写一个 Servlet,它将从外部文件夹中读取文件并将它们流式传输到客户端:本质上,它充当客户端和外部文件系统之间的代理。这就像下面这样的东西,您可以简单地使用它来调用:

<img src="/pathToMyImageServlet?imageId=123"/>

Servlet:

public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String imageId = request.getParameter("imageId");

        /*
        File file = new File("E:/my work/images/" + imageId);
        FileInputStream in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();

        byte[] buf = new byte[1024];
        int count = 0;

        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        */

        byte[] imageData = ....// data from db for specified imageId
        OutputStream out = response.getOutputStream();
        out.write(imageData);
        out.flush();
        out.close();
        //in.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

<context> 添加到 tomcat/conf/server.xml 文件。

<Context docBase="c:\images" path="/project/images" />

这样,您应该可以在

下找到文件(例如c:/images/NameOfImage.jpg)

http://localhost:8080/project/images/NameOfImage.jpg