当前位置: 首页 > 知识库问答 >
问题:

如何从jsp本地路径显示图像

越安翔
2023-03-14
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
 public void init() throws ServletException {

    this.filePath = "/files";
}

protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do get");

    // Get requested file by path info.
    String requestedFile = request.getPathInfo();

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        // Do your thing if the file is not supplied to the request URI.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do post");

}


private static void close(Closeable resource) {
    if (resource != null) {
        try {
            resource.close();
        } catch (IOException e) {
            // Do your thing with the exception. Print it, log it or mail it.
            e.printStackTrace();
        }
    }
}

在web.xml中,servlet条目如下所示,

<servlet>
<description>
</description>
<display-name>FileServlet</display-name>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.mypackage.FileServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>

在Jsp中,我有如下img标记,

<img alt="Image" src="file/D:/uploads/img14.jsp" width="160" height="160"    class="img-thumbnail">

我想我在img标记的src属性上犯了错误,谁能说出我在这里犯的错误。

共有1个答案

梅飞宇
2023-03-14

看来您误解了Balusc关于这一点的帖子:FileServlet。在这种情况下,您将在磁盘中有一个用于服务器文件的基本路径(在服务器中的web应用程序文件夹路径之外),然后您的URL中使用的路径将用于在此基本路径中搜索。请注意Balusc的示例如何调用资源:

<a href="file/foo.exe">download foo.exe</a>

其中:

>

  • 文件是servlet的URL模式。在web.xml配置中注意到:

    <servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/file/*</url-pattern>
    </servlet-mapping>
    

    URL/foo.exe的其余部分是服务器硬盘中文件的位置。这可以通过使用httpservletrequest.html#getpathinfo轻松获得

    代码的这一部分注意到了这一点(注释是我的):

    public void init() throws ServletException {
        this.filePath = "/files";
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        // Get the file path from the URL.
        String requestedFile = request.getPathInfo();
    
        //...
        //using filePath attribute in servletclass as the base path
        //to lookup for the files, using the requestedFile
        //path to seek for the existance of the file (by name)
        //in your server
        //decoding the name in case of GET request encoding such as
        //%2F => /
        File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
        //...
    }
    

    然后,当有这样的请求时(在您视图中的HTML代码中):

    <img src="files/img/myimage.png" />
    
    - /  <-- root
      - /files <-- this is the base file path set in init method in your servlet
        - /img
          - myimage.png
    

    更多信息:

      null

  •  类似资料:
    • 在标记的src中传递的图像路径有一些问题。 在我的数据库中,我有用户图像的Linux绝对路径。我得到这个值并放入“src”属性中。 我有一个路径,例如: null 我需要知道的是我要做什么? 我必须改变Jetty的配置吗?我必须用Java运行一些代码吗? 通过谷歌搜索,我变得更加困惑。我想要个解释。 谢谢你,巴卢斯!豪豪乌豪阿

    • 我正试图通过adb shell在我的三星Note 3上显示本地图像。 ,但仍然不起作用。有人能帮我吗,真的很感激!

    • 我已成功将图像上载到我的上载目录。这就是结构 公共网页- 现在,我在DB记录中存储的路径是: ./上传/上传图片。gif 但当我这么做的时候: 它仍然没有显示任何东西。图像路径内容为/上传/上传图片。gif。 我正在尝试将图像加载到位于以下位置的视图中: 公共网页- 我会非常感激你的帮助。

    • 所以我是Android编程的新手,我正在尝试制作一个能够实时处理图像的应用程序。我已经实现了文档中的预览用例以及ImageAnalysis用例。目前,预览显示在上,但我希望在显示图像之前对图像进行处理,因此简而言之,我希望在方法中对帧做一些处理,然后显示此帧,而不是CameraX预览。 顺便说一句,使用CameraX这样做有意义吗?最后,我想使用OpenCV进行处理,但我选择了CameraX,因为

    • 如何在数据库中的jsp文件中显示图像? 下面的JSP代码:- 我们将从数据库中提取的图像存储在哪里? 任何人都可以帮忙吗?

    • 问题内容: 我有一个代码可以显示员工图表。 数据(名称,电话,照片等)存储在SQLServer中,并通过JSP显示。可以正常显示数据,但图像.jpg(存储在IMAGE = BLOB列中)除外。 顺便说一句,我已经显示了图像(请参见下面的代码),但是我不知道如何将其放在.css定义的区域中(也请参见以下代码),因为图像是通过resultSet被加载到浏览器的整个页面中。 有谁知道我如何“构图”图像?