在JSP中显示本地磁盘映像(web上下文之外的映像)



我使用servlet使.JSP页面中的图像路径可访问

public void nova() {
        System.out.println("Nova Certidão");
        certidoes = new File("C:\imagens\").listFiles();
        List<String> paths= new ArrayList<String>();
        for (File arquivo : certidoes) {
        paths.add(arquivo.getPath());
        }
        result.include("files", caminhos);
    }

现在在页面中,我可以访问arraylist文件中磁盘中的文件路径

在jsp中,我用这个来显示图像:

<c:forEach items="${files}" var="files">
${file} - 
<img src="/getImage/${file}" height="42" width="42"> 
<br>
</c:forEach>

我的getImage是这样的:

@Get("/getImage/{path}")
public void getImage(String path) {
    //here will come all the way to send the stream of the image if i receive the path
    System.out.println(path);
}

但它不起作用,因为它创建了一个奇怪的请求图像路径:

它创建:

/getImage/C:/imagens/image1.jpg

所以它不起作用,如果我手动键入:/getImage/image1,我会正确地显示系统,我认为它不适用于文件路径,因为/(我认为这很明显),但我不知道如何解决这个

您需要将图像添加到Web应用程序根目录的子目录中。

我假设您的应用程序根是{web_apps}/yourapp。在这个目录下,您将有一些子目录,如WEB-INF、样式、图像。

将您的所有图像放入/yourapp/images/(此文件夹可从公共文件夹访问)。

在JSP 中

<img src="${pageContext.request.contextPath}/images/${file}" height="42" width="42" /> 

更新

由于图像位于一个固定文件夹中,而该文件夹不在Web应用程序根目录中,因此我们无法使用上述解决方案。

以下是正确的解决方案:

  1. 使用DES/AES加密将图像的路径(绝对路径/相对路径)转换为VALID URL变量-输出可以是Base16、Base64编码。

  2. 将based16、Base64编码路径转换回public void getImage函数中图像的路径

    @Get("/getImage/{path}")     
    public void getImage(String path) {
        // path is in based16/Base64 encoding
        String pathOfImage = functionToConvertEncodedPathToRealPath ( path)
    }
    

最新更新