2015-10-20 135 views
0

我提到了这个Q&A,但我无法做到我想要的。检查图像中是否存在Java

我想显示一个图像,如果这个图像的路径存在和其他东西,如果图像路径不存在。所以我这样做:

<% String filePath = photoPath + nom.toLowerCase().replace(' ', '_') +"_"+prenom.toLowerCase().replace(' ', '_') + ".jpg"; 
    Path path = Paths.get(filePath); 
    if(Files.exists(path)) { 
%> 
<img name="" src="<%=filePath %>" width="96" height="120" alt=" Photographie de <%=prenom%> <%=nom%>"> 
<% } 
else { %> 
    <%=filePath %> 
    <img name="" src="<%=filePath %>" width="96" height="120" alt=" Photographie de <%=prenom%> <%=nom%>"> 
<% 
} 
%> 

在这里,我尝试在if和除了我展示路径和else图像0​​同样的事情。我的输出是else语句,因此我的图像不应该显示,但会显示图像。

有什么想法?

+1

两个分支都使用'<%= filePath%>'? – MadProgrammer

+0

@MadProgrammer是的,这只是为了测试图像是否存在。问题是图像显示在else语句中。所以如果显示图像,它不应该在其他地方,对不对? –

+0

如果文件存在,则返回'else'。如果该文件存在,则将其显示为图像。问题是什么? – EJP

回答

1

问题在于filePath适用于img-src,它是相对于Web应用程序的根文件夹的路径。对于文件系统路径,存在getRealPath()

<% 
    String filePath = photoPath + nom.toLowerCase().replace(' ', '_') 
     +"_"+prenom.toLowerCase().replace(' ', '_') + ".jpg"; 
    Path path = Paths.get(request.getServletContext().getRealPath(filePath)); 
    if (Files.exists(path)) { 
%>