0

I referred to this Q&A but I'm not able to do what I want.

I want to display an image if the path of this image exist and something else if the image path doesn't exist. So I did this :

<% 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%>">
 <%
 }
%>

Here I try the same thing in the if and else except that I show the path and the image in the else. My output is the else statement so my image shouldn't be displayed but the image is displayed.

Any idea ?

Community
  • 1
  • 1
Simon M.
  • 2,244
  • 3
  • 17
  • 34
  • 1
    Both branches are using `<%=filePath %>`?? – MadProgrammer Oct 20 '15 at 12:06
  • @MadProgrammer Yes, this is just to test if the image exist. The problem is that the image is displayed in the else statement. So if the image is displayed, it shouldn't be in the else, right ? – Simon M. Oct 20 '15 at 12:12
  • The 'else' is reached if the file exists. If the file exists you are displaying it as an image. What's the question? – user207421 Oct 20 '15 at 12:13
  • @EJP Wrong copy/paste sorry, Edited – Simon M. Oct 20 '15 at 12:16
  • What's in filePath? Is it a relative path? – jaudo Oct 20 '15 at 12:22
  • @j0d0 I tried with absolute and relative path – Simon M. Oct 20 '15 at 12:27
  • @JiriTousek I know, it's to check if the `.exists` work but it seems to not because it display the image in the else statement except that the else statement should work if the image dosn't exist, right ? – Simon M. Oct 20 '15 at 12:32
  • Please clarify your question, and example. Which case is executing? Can you use less similar output for the 2? – kervin Oct 20 '15 at 12:35
  • @Yvette The thing is I just have to add the delete method to an object to an existing app, but I have 0 experience with, so I really don't know how to start – Simon M. Oct 22 '15 at 12:00

1 Answers1

1

The problem is that filePath is for img-src, a path relative to the web application's root folder. For the file system path, there exists getRealPath().

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