• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

how to retrieve images on a jsp page

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am storing files in a Acess SQL server database as images . I would like to retrieve the image on my jsp page when you click on the document id. anyone has used this before and know hoe to retrieve stored document from the database???
Any help will be really appreciated.
 
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Store ur photographs in binary format in database, eg BLOB in oracle.
Fetch data from database
SELECT IMAGE_FILE FROM table_Name where employeeid = "123";
fetch data from database in binary format using java io streams
response.setContentType("image/jpeg");
ServletOutputStream o= response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(
objResultSet.getBinaryStream("IMAGE_FILE") );
byte bindata[] = new byte[1024];

int bytesread = 0;
while ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
{ o.write(bindata);}
set src of above jsp in another jsp where photograph has to be put in
document.forms[0].imgPhoto.src="....../Image.jsp";
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that serving binary data such as images should be done via a servlet. JSP are strictly for serving character data.
Bill
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your replies. I tried to apply what you said but I am getting
cannot resolve symbol : variable Response
location: class org.apache.jsp.PublicationDetails_jsp
Response.ContentType = "image/pdf";
Here is the code in the jsp page:
<body>
<p>
<%@ page import="java.sql.* "%>
<%@page import ="java.util.*"%>
<%@page import ="java.io.*"%>
<%!Statement s;%>
<%!String publicationNumber="";%>
</p>
<%
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc dbc:AcessCore");
String st = request.getParameter("id");
String sql = "SELECT Docment FROM Publications WHERE PublicationID = '" +st+"'";
Statement s= con.createStatement();
ResultSet rs = s.executeQuery(sql);
Response.ContentType = "image/pdf";
ServletOutputStream o= response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream("sql"));

byte bindata[] = new byte[1024];
int bytesread = 0;

while ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
{ o.write(bindata); }

rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException e1) {
// JDBC driver class not found, print error message to the console
System.out.println(e1.toString());
System.out.println("oh lala!");
}
catch (SQLException e2) {
// Exception when executing java.sql related commands, print error message to the console
System.out.println(e2.toString());
System.out.println("try again");
}
catch (Exception e3) {
// other unexpected exception, print error message to the console
System.out.println(e3.toString());
}
%>

Is this code correct so far? why am I getting that error?
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please pay attention:

Response.ContentType = "image/pdf";
ServletOutputStream o= response.getOutputStream();


The immediate cause of the error is the upper case R in Response.
However, you are doomed to failure because you are trying to send binary data from a JSP. A JSP already has obtained an output stream from the response by the time your code tries to run - it is the "out" variable which is a JspWriter - for character data, not binary data.
I really don't understand why people keep trying to do this - servlets are not that hard to understand.
Bill
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I actually tried to use a servet but it's giving 11 errors: package javax.servlet does not exist, package javax.servlet.http does not exist,cannot resolve symbol class HttpServlet , class HttpServletRequest,class HttpServletResponse ,class ServletException ,class ServletException ,class ServletOutputStream ,class RequestDispatcher ,method getServletContext ()

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PublicationServlet extends HttpServlet
{//Variables
private String publicationNumber="";
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
publicationNumber = request.getParameter("id");
response.setContentType("application/pdf");
PrintWriter out = response.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc dbc:AcessCore");
String sql = "SELECT Docment FROM Publications WHERE PublicationID = '" +publicationNumber+"'";
Statement s= con.createStatement();
ResultSet rs = s.executeQuery(sql);
response.setHeader("Content-disposition","attachment; filename=" +
"Example.pdf" );
ServletOutputStream o= response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream("sql"));
byte bindata[] = new byte[2048];
int bytesread = 0;
while ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
{ o.write(bindata); }
rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException cnfe)
{ cnfe.printStackTrace();
}

gotoPage("/confirmation.jsp", request, response); }

// Method to get the request dispatcher and forward the request to the following address
public void gotoPage(String address, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}

 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My classpath :
CLASSPATH=.;C:\j2sdk1.4.2\bin;.;%CATALINA_HOME%/webapps/CoreData/web-inf/classes;. %CATALINA_HOME%/webapps/coredata;. C:/tomcat/tomcat/webapps/coredata/web-inf/classes/Helper;%CATALINA_HOME%\common\lib\servlet.jar;.;%JAVA_HOME%\jre\lib\rt.jar;.;%JAVA_HOME%\lib\tools.jar;.;
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm assuming those are compilation errors - your classpath must include servlet.jar - thats where the javax.servlet etc classes live.
DO NOT use a PrintWriter - thats for characters - a pdf has to be sent in binary form.
You want to do response.getOuputStream - see the JavaDocs for javax.servlet.Response
Bill
 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
William,
I don't know if I'd be that strict in your statement about using a servlet. A JSP will suffice for streaming binary data. Here's a JSP I use for streaming binary data:
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your replies.
I would like to know what represents the "word.exe" in the code you just gave me. Or "Example.pdf". Because I want my documents to be opened as pdf but there is a different file for each publication number. So how do I make it general so that it's opens the document it actually finds on the select method.Because it's trying to look for the example.exe document. I can't name each and every document.
Here is the code again:
response.addHeader("Content-disposition",
"attachment; filename=" +
"Example.pdf" );
File f = new File("c:\\Example.pdf");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc dbc:AcessCore");
String st = request.getParameter("id");
String sql = "SELECT Document FROM NEPRUPublications WHERE PublicationID = '" +st+"'";
Statement s= con.createStatement();
ResultSet rs = s.executeQuery(sql);
;
FileInputStream fis = new FileInputStream(f);
ServletOutputStream o= response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream("sql"));

byte bindata[] = new byte[2048];
int bytesread = 0;

while ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
{
fis.close();
o.write(bindata);
o.close();}

rs.close();
s.close();
con.close();

Note that my files are in the database. How do Ido for this : File f = new File("c:\\Example.pdf");
Thanks
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Joe - I suspect that would not work in all JSP implementations since it appears to depend on the absence of text content to prevent creation of the out variable as a PrintWriter. If the JSP compiler inserts a call before your code starts to response.getOutputStream, you would get the IllegalStateException.
Bill
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
People, you saw the servlet I have and also the jsp. None of them work so far. The jsp tries to open the Example.pdf file which I don't have. How do I make it open the file contained in my database??
Waiting for your help
Thanks :roll:
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am getting this error now :
org.apache.jasper.JasperException: getOutputStream() has already been called for this response
I tried to catch the java.lang.IllegalStateException but it's then complains of catching it twice.
My code still same:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc dbc:AcessCore");
String st = request.getParameter("id");
String sql = "SELECT Document FROM NEPRUPublications WHERE PublicationID = '" +st+"'";
Statement s= con.createStatement();
ResultSet rs=null ;
response.setContentType("application/pdf");
ServletOutputStream o= response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream("sql"));
byte bindata[] = new byte[2048];
int bytesread = 0;
while ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
{
o.write(bindata);
o.close();}
rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException e1) {
// JDBC driver class not found, print error message to the console
System.out.println(e1.toString());
System.out.println("oh lala!");
}
catch (SQLException e2) {
// Exception when executing java.sql related commands, print error message to the console
System.out.println(e2.toString());
System.out.println("try again");
}
catch (Exception e3) {
// other unexpected exception, print error message to the console
System.out.println(e3.toString());
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

org.apache.jasper.JasperException: getOutputStream() has already been called for this response


That is exactly what I have been trying to tell you.
JSP assume you are going to be sending characters - the JSP compiler provides the automatic "out" variable which is a JspWriter - already opened under most circumstances. A JspWriter is like a PrintWriter specialized for the JSP environment.
Read the JavaDocs for javax.servlet.ServletResponse.
Bill
[ February 27, 2004: Message edited by: William Brogden ]
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
orelia,
Listen to William for he is wise. Using a JSP for non-text content is like using a hammer to set a screw. While it may be made to work in some cases, it's a poor tool for the job and the results aren't usually pretty. Do yourself a favor and explore his recommendation to use a servlet whenever producing binary data.
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I actually also have a servlet but the thing is I am not using it because of this
out.write("<a td img href='PublicationDetails.jsp?id=" + publicationNum + "'><font face= verdana size=-1>"+publicationNum+"</td>");
I can't send the id to the servlet, it's giving me an error. Plus if I just just use <form action=servlet method post>on my jsp, there is no href .
My servlet is in my previous messages. please help. I am so desperate now and I am running out of time. My contract is finishing next month and this is my last problem before implementation(well, I guess).
 
William Brogden
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your img tag must have a src="someurl" where someurl directly addresses the servlet that is going to send the image data. You can include in that URL enough information to tell the servlet what to send OR you could put that information in the session. The servlet code you posted has the line:

This is WRONG! you can't send open the response stream twice and you cant send binary data with a writer. You must drop the code that gets a writer.
If this was my problem I would write a plain HTML page with a hard coded IMG tag to test the image serving servlet. Trying to debug the combination of JSP + servlet + database is just too confusing.
Bill
 
orelia hans
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I give up. I am not gonna try to retrieve the files from the database. Instead, I will se the code bellow. The lines that confuse me are bolded. Frist the problem is that even when my publication number is equal to NB10, or anything else the line system.out.println(path) gives me path=nothing.It always falls to path=nothing. Why is that?
And also am having a "unclosed character litteral" error when I write
new File('"+path+"'); How do I do it instead

<%!String publicationNumber="";%>
<%!String path;%>
<%@ page contentType="octet/stream" %>
</p>
<%
try {
String st = request.getParameter("id");
System.out.println(st);
path="";
if(st=="NB10")
{
path="C:\\My Documents\\competition.pdf";
}
else if(st=="NP2")
{
path="C:\\My Documents\\proletion.pdf";
}
else
{
path="nothing";
}
System.out.println(path);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "filename=competition.pdf");

File f = new File(path);
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[(int)f.length()];
fis.read(buffer,0,(int)f.length());
fis.close();
ServletOutputStream os = response.getOutputStream();
os.write(buffer);
os.close();

}
catch (Exception e3) {

System.out.println(e3.toString());
}
%>
Thanks
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic