一尘不染

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

jsp

我试图显示图像抛出JSP。图像存储在本地路径中,因此我编写了一个servlet
get方法来检索图像,并在图像标签的src属性中给出了servlet名称和图像路径作为servlet的参数,这是我的代码,

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属性中犯了错误,谁能说出我在这里犯的错误。


阅读 318

收藏
2020-06-10

共1个答案

一尘不染

看来您对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>

这是在代码的这一部分中指出的(注释是我的):

    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
2020-06-10