I am working on an assignment in which I have to provide a user login after which he will be directed to a page where he can upload images and all of his previous + new images will be displayed below in a table. So the structure of my application is like this...
(trimmed most of the code for clarity)
JSP file that allows upload and displays the image
<p>Please select an image file to upload(Max file size 1 MB)</p>
<%
Integer userId = 0;
userId = (Integer) session.getAttribute("userId");
%>
<%
String errorMessage = (String) request.getAttribute("error");
if (errorMessage != null) {
out.print("<h4> " + errorMessage + "</h4>");
}
%>
<form action="imageupload" enctype="multipart/form-data" method="post">
<br /> <input type="file" name="uploader" id="uploader" /> <br /> <br />
<input type="submit" /> <input type="button"
value="clear" onClick="clear()" />
</form>
<br />
<h4>Uploaded Images</h4>
<br />
<table width="80%">
<tr>
<th>S No.</th>
<th>Name</th>
<th>size</th>
<th>Preview</th>
<th>Actions</th>
</tr>
<%
UserImagesDAOImplementation userImages = new UserImagesDAOImplementation();
List<Image> images = (List<Image>) userImages.getUserImages(userId);
for (Image image : images) {
%>
<tr>
<td><%=image.getSn()%></td>
<td><%=image.getImageName()%></td>
<td><%=image.getSize()%></td>
<td><% session.setAttribute("image",image.getImage() ); %><img src="toimage" height="100px" width="100px" /></td>
<td><img src="img/edit.png" /> <img src="img/url.png" /></td>
</tr>
<%
}
%>
</table>
<br />
Total space used: <%= (userImages.getSizeUsage(userId)/1024) %> KB / 10 MB
the "toimage" servlet that returns the image
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Byte[] image = (Byte[]) session.getAttribute("image");
int len = image.length;
byte[] imageData = new byte[len];
for(int i=0; i < len; i++) {
imageData[i] = image[i];
}
response.setContentType("image/jpg");
response.getOutputStream().write(imageData);
response.getOutputStream().flush();
response.getOutputStream().close();
}
My problem is that it displays the last image in the list in all the table rows and after uploading some other image it displays that new image in every row.
I am not very confident about my design for the site but this is the first time I am working with JSP. I decided to get the image list inside JSP as I will have to perform some more operations on it later on. I guess the problem is either in setting the session variable or the src servlet being called in the end. Whatever it is, can someone please explain the typical flow of events in this design.
Edit: Putting a print statement inside the "toimage" servlet proves that it is being called just once. So how can I make the JSP loop to call the image src every time ??