Avatar of mytilig
mytilig
 asked on

How to read pictures from a remote windows server and render through JSP

I have the following requirement:

Display pictures residing on a windows server onto a unix server (the unix server has the webserver).
The pictures all have read permissions.

Through java/jsp, how can I read image files from a remote server and display on a web page.

What are my options to do this?

Thanks.
JSP

Avatar of undefined
Last Comment
pzepernick

8/22/2022 - Mon
pzepernick

What kind of access do you have from the unix server to the windows server?  Do you have a folder mounted or can you get to them through FTP?

Once you can get a reference to the file to display you will want to do something like this in the jsp which is displaying the image.  This can be a path to a jsp or servlet:

<img src="myPicDisplay.jsp?imageToShow=data" />

You are probably going to need to pass some sort of param to indicate which image the page needs to grab from your windows box.

Then in the myPicDisplay.jsp you would do something like the following:
        InputStream input = new FileInputStream(new File("/mymount/myimage.jpg"));
        OutputStream output = null;
       

              // Set the content type
             response.setContentType("image/jpeg");
            
              // Get the outputstream
              output = response.getOutputStream();
      
              // Copy input to output
              byte[] oBuff = new byte[bufferSize];
              int iSize = 0;
              while (-1 != (iSize = input.read(oBuff))) {
                  output.write(oBuff, 0, iSize);
              }
      
              // Flush
              output.flush();


Paul
bpmurray

Try mapping the address in your web.xml and processing it as a special image servlet:

Your JSP contains:
     <img src="/winimages/myimage.gif" />

Your web.xml contains:
        <servlet>
            <servlet-name>Image Servlet</servlet-name>
            <servlet-class>
                    com.foo.bar.ImageServlet
                </servlet-class>
            <load-on-startup>1</load-on-startup>
      </servlet>
         ....
      <servlet-mapping>
            <servlet-name>Image Servlet</servlet-name>
            <url-pattern>/winimages/*</url-pattern>
      </servlet-mapping>

The servlet class then contains:
   public class ImageServlet extends HttpServlet implements Servlet {
        private static final String MOUNTPOINT = "/mnt/WindowsMachine/C/images/";
        private static final String PATTERN       = "/winmages/";
      private ClassLoader classLoader = null;


      public void init(ServletConfig config) throws ServletException {
            super.init(config);
            classLoader = getClass().getClassLoader();
        }
      public void destroy() {
            super.destroy();
      }
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                     String fname = req.getRequestURI();
                fname = this.MOUNTPOINT + fname.substring(fname.lastIndexOf(this.PATTERN) + this.PATTERN.length());
                InputStream input = new FileInputStream(new File(fname));
               
                byte[] buffer = new byte[0];
                int readLen = 0;
                while((readLen = input.read(buffer)) > 0) {    // Read the entire file ...
                    int newLen = buffer.length + readLen;
                    byte[] newBuff = new byte[newLen ];
                    System.arraycopy(bytes, 0, newBuff, 0, buffer.length);
                    System.arraycopy(buffer, 0, newBuff, buffer.length, read);
                    buffer = newBuff;
                }
                resp.getOutputStream().write(bytes);        // ... and write it out
                input.close();
        }

}
mytilig

ASKER
Hi Paul,
The above code was giving me error at output.write. I modified it slightly - like this-


      File f = new File("/path/pic.jpg");
             // Set the content type
            response.setContentType("image/jpeg");
             OutputStream outStream = response.getOutputStream();
          try
             {
        label1:     System.out.println("......len is " +f.length());
        label2:      DataInputStream dis = new DataInputStream(new FileInputStream(f));
              System.out.println("....got here...");
           byte picture[] =  new byte[dis.available()];
           dis.read(picture);
           dis.close();
           outStream.write(picture);
           outStream.flush();
             outStream.close();
             } catch(java.io.IOException ie) { System.out.println("....Exception caught"); }

I am getting the error
Servlet.service() for servlet jsp threw exception   java.lang.IllegalStateException: WEB3024: getOutputStream() has already been called for this response   at org.apache.catalina.connector.ResponseBase.getWriter(ResponseBase.java:841)   at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:165)   at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:184)   at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:176)   at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:187)   at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:204)   at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:199)  

This error is reached on label2.
btw The length on label1 is printed as zero. but I know for sure that the path to the image is visible to the webserver.
Any thoughts?
Thanks in advance!
 
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
pzepernick

mytilig,

I researched the error a little bit and it is being caused by the container calling response.getWriter() internally on the JSP page.  I found the following fix on a google search:

>>at the beginning of the page, the compiled servlet will actually have an out.write("\r\n") generated between those two >>lines. this means that the response.getWriter() is called, which is what causes the IllegalStateException (u can't call both >>getWriter() and getOutputStream()). So my solution was to make sure there are no whitespaces of any kind before (or >>?after?) the call to getOutputStream().

http://forum.java.sun.com/thread.jspa?forumID=45&threadID=373667

So you would want to make sure you do the following in the JSPL

<%@ page import ... %>
<%
   OutputStream outStream = response.getOutputStream();
    File f = new File("/path/pic.jpg");
             // Set the content type
            response.setContentType("image/jpeg");
          try
             {
        label1:     System.out.println("......len is " +f.length());
        label2:      DataInputStream dis = new DataInputStream(new FileInputStream(f));
              System.out.println("....got here...");
           byte picture[] =  new byte[dis.available()];
           dis.read(picture);
           dis.close();
           outStream.write(picture);
           outStream.flush();
             outStream.close();
             } catch(java.io.IOException ie) { System.out.println("....Exception caught"); }
%>

Make sure there is no space between your imports and where the code starts.  Then make sure the OutputStream is the first thing created.  After the code ends, make sure there are not returns or white space.  

Maybe the length problem is caused by a permissions issue.  Do you have read permissions for the user the java server is running under?  I would check to see what exists() returns on the file object.

Paul
mytilig

ASKER
Thankyou for all your time!
I will try this and let you know in the next 2 hours.
Regards,
Mytili
mytilig

ASKER
Hi Paul.
I removed some newlines, but still getting the illegal state exception. The error message remains
Servlet.service() for servlet jsp threw exception   java.lang.IllegalStateException: WEB3024: getOutputStream() has already been called for this response  


Photo.jsp
-----------------
<%@ page import="java.io.FileInputStream" %><%@ page import="java.io.InputStream" %><%@ page import="java.io.OutputStreamWriter" %><%@ page import="java.io.File" %><%@ page import="java.io.OutputStream" %><%@ page import="java.io.DataInputStream" %> <%  
    File f = new File("http://domain.com/photos/new.jpg");
            response.setContentType("image/jpeg");
             OutputStream outStream = response.getOutputStream();
          try {
             System.out.println("......len is " +f.length());
              DataInputStream dis = new DataInputStream(new FileInputStream(f));
              System.out.println("....4");
           byte picture[] =  new byte[dis.available()];
           dis.read(picture);
           dis.close();
           outStream.write(picture);
           outStream.flush();
             outStream.close();
             } catch(java.io.IOException ie) { System.out.println("....Exception caught"+ie); }
      %>

DisplayPhoto.jsp
-----------------

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<img src="Photo.jsp" />
</body>
</html>

I have another question- File exists is returning false. The url to the picture http://domain.com/photos/new.jpg brings up the picture. (Picture resides on another windows server, and I am accessing it through a url rather than mounting or ftp)
So I am not understanding why it is not able to read the file..
Thanks.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER CERTIFIED SOLUTION
pzepernick

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
mytilig

ASKER
The pictire is displaying correctly after I changed to URL to read the file.
But on looking through the logs, I realize that the illegal state exception still remains.
Would it be ok to ignore this error message?

pzepernick

If everything is working okay then it may be something you could just ignore.  To get rid of the message, you may want to consider using a servlet instead of a JSP.

Paul