Asif
Asif

Reputation: 5038

Image Upload and Display in JSP

I've learned and implement successfully that how to upload images on server disk with servlet from Here and now trying to show the image on another jsp userProfile.jsp with the help of following code :

<img src="<jsp:include page='WEB-INF/jspf/profileImage.jspf' />" height="175" width="175" /> 

and code of profileImage.jspf is as follows:

OutputStream o = response.getOutputStream();
InputStream is = new FileInputStream(new File("../files/backPetals.jpg"));
byte[] buf = new byte[32 * 1024]; 
int nRead = 0;
while( (nRead=is.read(buf)) != -1 ) {
    o.write(buf, 0, nRead);
}
o.flush();
o.close();
return; 

but it does not works.. Any other ways to display the image from disk on jsp together with other matter on page? I've saved my images on /files directories on the application root folder.

Upvotes: 2

Views: 13934

Answers (2)

JB Nizet
JB Nizet

Reputation: 691635

The syntax of an img tag is <img src="url_of_the_image" .../>. What you're doing is <img src="contents_of_the_image_file" .../>.

You need to generate a URL to a servlet, and this servlet needs to open the image file and send its content to the output stream. You can't download an HTML file and an image in a single HTTP request.

Upvotes: 1

BalusC
BalusC

Reputation: 1108632

There are several serious mistakes in the approach:

  1. You should not store the uploaded file in the application root folder. They will all get lost whenever you redeploy the WAR (simply because those files are not contained in the original WAR file.

  2. The <img src> should not contain the raw image content, but it should contain an URL which returns the file content. E.g.

    <img src="profilePictures/${user.profilePictureFilename}" />
    
  3. You should not use JSP to write binary data to the response. Use a servlet instead. Or if you can, just add the path to uploaded files as another webapp context.

Here are several answers which should help you in the right direction:

Upvotes: 3

Related Questions