Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Display SQL Server Image Data Type

 
Mitchell Baron
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm trying to display an image stored in a SQL Server 2000 image type database column. When the followinbg code is executed, the browser seems to find the image but only displays a RED X.

I understand that storing images in the database is not a good idea but do not have a choice in this case.

Does anyone have any suggestions I could try as I've never done this in Java/JSP?

Thank you!

int AccountID = commonNet.getInt(request.getParameter("AccountID"));
String strContentType = request.getParameter("strContentType");
if ((strContentType==null)||(strContentType.equals(""))) {
strContentType="image/gif";
}

byte[] imgData = null;
String strSQL = "";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

conn = globalNet.openDbConnection();
stmt = conn.createStatement();
strSQL = " SELECT imgPhoto " +
" FROM Contact " +
" WHERE AccountID = " + AccountID;
rs = stmt.executeQuery(strSQL);
if (rs.next())
{
imgData = rs.getBytes(1);
}
rs.close();
stmt.close();

response.setContentType(strContentType);
response.setContentLength(imgData.length);
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();


[ August 08, 2008: Message edited by: Mitchell Baron ]

[ August 08, 2008: Message edited by: Mitchell Baron ]
[ August 08, 2008: Message edited by: Mitchell Baron ]
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will be better off reading the image in from the database using rs.getBinaryStream() rather than the rs.getBytes() method.

An example might be:


This is mostly pseudo code, I haven't written one of these image servlets before, so the code isn't tested. But it shows most of the key points. I also don't know if setting the content-disposition for the images is necessary (I know it is for downloading files, so I kept it here...).
 
Mitchell Baron
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using rs.getBinaryStream() worked!!! It did not seem to need the content-disposition setting.

Many thanks for the suggestion!

Mitchell
[ August 10, 2008: Message edited by: Mitchell Baron ]
 
Dave Wingate
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mitchell, you might find this tutorial on serving MIME content useful.
 
Mitchell Baron
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Dave. That is helpful!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic