user5681278
user5681278

Reputation:

Tomcat - display Image inside of WEB-INF

I am currently developing a JSP/Servlet application and dont want private pictures to be accessible by other users that dont own them.

My problem is that users can access assets by simply rewriting paths in their html viewer, thats why I had to put the pictures into the WEB-INF Folder, to not make them accessible from the outside.

the pictures are located in /tomcat/myProject/ROOT/WEB-INF/Users/%userName%/

But now that the images are inside of WEB-INF I cant load them with my servlet.

Anybody knows how to access the picture, save it in a session attribute and only make them visible to the user that requested the JSP?

Edit: I took Kaleb Brasee's code and inserted it into my method:

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ...
    BufferedImage image = ImageIO.read(new File(profilePicturePath));
    OutputStream responseStream = response.getOutputStream();
    ImageIO.write(image, "JPEG", responseStream);
    //session.setAttribute("profilepicture", PLACEHOLDER);  //PLACEHOLDER should be replaced by the actual Image, but I dont know how to do this
    //response.sendRedirect("/Index"); //doesnt get executed, because ImageIO.write(...) already commits a response before this line of code is reached
}

When executed, the code above will show a html page with a imgtag containing the image from the WEB-INFfolder, but nothing else.

This is not the desired behaviour, I need to save the ImageIO.write(...) output as a session attribute, so I can insert it into a specific place inside of my /Index JSP Page.

Any ideas on how to solve this?

Upvotes: 1

Views: 884

Answers (1)

Kaleb Brasee
Kaleb Brasee

Reputation: 51925

You can create a servlet that takes an image ID as a request parameter. If the user has authorization to view file then write it to the output stream, otherwise return an HTTP error response.

The ImageIO.write method is useful for writing a loaded image to a HttpServletResponse OutputStream.

I have used some code before that loads a PNG and writes it out to a response as follows:

response.setContentType("image/png");
BufferedImage image = generateImage(); // my custom method to create an image
OutputStream responseStream = response.getOutputStream();
ImageIO.write(image, "PNG", responseStream);

Upvotes: 2

Related Questions