• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 375
  • Last Modified:

Jsp Image not displaying after rewritting

Hi To All,
I am reading and creating a image in struts action class.It is working but when redirecting to .jsp page it is not reflecting the rewritten image .BUT after refreshing the IE window it shows the updated image.My code is
------ Action class -------
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream stream = file.getInputStream();
                     //write the file to the file specified
      OutputStream bos = new FileOutputStream(imageStorePath);
                        
      
                    //only write files out that are less than 1MB
                   if (file.getFileSize() < (4*1024000)) {
                        byte[] buffer = new byte[8192];
                        int bytesRead = 0;
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                            bos.write(buffer, 0, bytesRead);
                        }

---.jsp page-----
  <logic:equal name="ActionForm" property="imagefile" value="true">  
  <IMG src="/ilmp/img/<%= fileName%>" width="150" height="150"></IMG>
 </logic:equal>

It is getting right file name and displaying images after refreshing.
Please help me to find out the problem
Thanks in advance
0
m_sharma98
Asked:
m_sharma98
  • 10
  • 8
1 Solution
 
TimYatesCommented:
Try changing the JSP page to:

<%
        // Set to expire far in the past.
        response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
%>
  <logic:equal name="ActionForm" property="imagefile" value="true">  
      <IMG src="/ilmp/img/<%= fileName%>" width="150" height="150"></IMG>
 </logic:equal>
0
 
m_sharma98Author Commented:
I have already tried that one BUT still not working...
Whether I ve to write file in different manner?
0
 
TimYatesCommented:
Why don't you just get a servlet to generate the image?

http://today.java.net/pub/a/today/2004/04/22/images.html
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
TimYatesCommented:
I can't see what you Action is doing...  does it limit images to 1Mb?
0
 
m_sharma98Author Commented:
Yes my checking for limit 1Mb and then reading a input file and writing that file to folder.If a file(file name) is not present it will give me the expected result BUT if it is already exists it will rewrite on that file AND in this situation it will not reflect the file to JSP page WITHOUT refreshing.
0
 
m_sharma98Author Commented:
Sorry for missing..
I mean my Action Class
0
 
TimYatesCommented:
>>  then reading a input file and writing that file to folder

Why don't you just have a servlet return the image to the browser directly?

The problem here (I think) is that image loading in browsers is asynchronous, so the browser will be loading the old image before your java method has had chance to update the image...

can't you just do:

    <img src="ImageParsingServlet"/>

then write the servlet to filter the image?
0
 
m_sharma98Author Commented:
Sorry but I didn't got you.
Can u plz elaborate it ...
Actually I cant forward the <img src="ImageParsingServlet"/> the servlet from Image Tag becoz it is a returning the same jsp so it will become a infinite loop
0
 
TimYatesCommented:
Is the action called before the page is shown to the user?

It's hard to tell from the small amount of code you posted...
0
 
m_sharma98Author Commented:
The image.jsp page is calling once from Action class when it is first loading with default image and after updating the image it is calling again by seperate Action class.
So after updating(updateImageAction.do)the image.jsp page is again calling by ActionForward.
0
 
TimYatesCommented:
can I ask what it is you are trying to do?  I may be able to think of a cleaner way of doing it :-)
0
 
m_sharma98Author Commented:
I am reading(if already exists) a .jpg file and overwriting it with new one AND if not exists generate a new file and write it.

----------------------
   /** Upload Image action : open ChangeImage.jsp**/
    public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
       HttpSession session=request.getSession();
   FORWARD_studentGoalBaseAction= "studentGoalBaseAction";
   
    /**When session Time out*/
        if(session.getAttribute("userid") == null){
        throw new SessionOutException();
          }
          
    StudentForm studentform = (StudentForm) form;  //StudentForm class
    javax.sql.DataSource dataSource;
    java.sql.Connection con=null;
        
    //retrieve the file representation
  FormFile file = studentform.getFileUpload();
    //retrieve the file name
 //   String fileName= file.getFileName();
 
     //retrieve the content type
      String contentType = file.getContentType();
    //retrieve the file size
    String size = (file.getFileSize() + " bytes");
   

// Get the locale and message resources bundle student.properties; get the file path for saving image
    MessageResources messageResources =  getResources(request, "re.MyResources");

    String data = null;
      /** generate file name as userid.gif **/
      String fileName=studentform.getUserid();
      fileName=fileName+messageResources.getMessage("upload.imgextension") ;//fileName with file extension .jpg  to store
      
   String imageStorePath = messageResources.getMessage("upload.filepath") + fileName;

//     String imageDeletePath = messageResources.getMessage("delete.filepath") + fileName;
        try {
                       dataSource = getDataSource(request);
                         con = dataSource.getConnection();            
                                   //retrieve the file data
                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream stream = file.getInputStream();
               
                        //write the file to the file specified
OutputStream bos = new FileOutputStream(imageStorePath);
                        
                          //only write files out that are less than 1MB
                   if (file.getFileSize() < (4*1024000)) {
                        byte[] buffer = new byte[8192];
                        int bytesRead = 0;
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                            bos.write(buffer, 0, bytesRead);
                        }
   
                                      }//end if
                   else {
           ActionMessages messages = new ActionMessages();       
             messages.add("maxLengthExceeded", new ActionMessage("error.maxLengthExceeded"));//add specific error with id
            saveMessages(request, messages);
            FORWARD_studentGoalBaseAction=FORWARD_studentImageChange;
                    }
              session.setAttribute("fileName", fileName);
              bos.close();
              baos.close();
                       //close the stream
                    stream.close();
                file.destroy();
                con.close();//close connection
            }  catch (Exception sqle) {
                 getServlet().log("Exception in StudentGoalEditBaseAction Class (Method FileUpload) : ", sqle);
                                }
         ActionForward forward=mapping.findForward(FORWARD_studentGoalBaseAction);
      return forward;            
    }//end method
----------------------
0
 
TimYatesCommented:
Can I check I've got this right then?

1) The user selects a file on their local machine to upload
2) This code checks the image is below a certain size, and if it is, overwrites (or creates) the image in a directory
3) There is an IMG tag which then shows this image to the user

And the problem is that the old image is still being shown (when the user updates the image)

Right?

Does it show the right image if a new one is created?

Sorry...I just want to make sure I have it right in my head ;-)  It's early, and I'm trying to write a CAB extraction tool...so my head's a bit fuzzy at the moment ;-)

More coffee required ;-)

Tim
0
 
m_sharma98Author Commented:
Yeah exactly it is the one
you got the point ...
0
 
TimYatesCommented:
can you try changing:

    <IMG src="/ilmp/img/<%= fileName%>" width="150" height="150"></IMG>

to:

    <IMG src="/ilmp/img/<%= fileName%>?t=<%= "" + System.currentTimeMillis() %>" width="150" height="150"></IMG>

?  That might help kick the caching...

Otherwise, it's looking like the IMG tag is getting executed BEFORE the image is saved...  which is odd :-/
0
 
m_sharma98Author Commented:
Thanks a lot TimYates
 <IMG src="/ilmp/img/<%= fileName%>?t=<%= "" + System.currentTimeMillis() %>" width="150" height="150"></IMG>
 is working perfectly...

But How it is ??? I didn't understand it yet..

Anyway thanks a lot..
0
 
TimYatesCommented:
Basically, it puts a query parameter on the URL of the image like so:

    /ilmp/img/whatever.gif?t=203847578484984

(the parameter passed is the number of milliseconds since 01/01/1970)

So the browser is fooled into thinking it's a new image it's going to be reading, so it actually bothers to fetch it (not from its cache) :-)

it's quite a useful little hacklet :-)

Glad we got it sorted!!  Good luck with it all :-)

Tim
0
 
TimYatesCommented:
if you "View Source" in your browser on that page, you will be able to see the parameter on the image

for that particular millisecond

the parameter will be different every time

so long as you don't refresh in the same millisecond ;-)

Good luck again!

Tim
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 10
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now