? : Using Java/Jsp/Servlets to insert & retrieve image from DB
843841Jun 22 2005 — edited Jan 21 2008Hello everyone,
Forgive me if this post does not belong in this forum...however, since I'm working with java/jsp/servlets I felt this forum may be of some help.
What I'm trying to accomplish:
1) insert an image into a database table column of BLOB type
2) retrieve that image and display it within a web browser for viewing
Languages I'm working with:
1) JSP
2) Servlets
3) Java
Database & Server Version:
1) Tomcat 4.1.29
2) Mysql 4.0.17
My process is as such:
1) html page with form field for selecting the image from the local computer, form action is set to "anything.upload" (which is my servlet on the localhost server), hit submit and the servlet processes the upload into the database.
2) servlet outputs a link for retrieval of the image from the db via another servlet
Here is the upload servlet snippet:
<--
File f = new File(item.getName()); // Create a FileItem object to access the file.
byte[] bytes = new byte[(int)f.length()];
FileInputStream fs = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fs);
bis.read();
PreparedStatement stmt = conn.prepareStatement("Insert into mytable values(?)");
stmt.setBytes(1, bytes);
int i = stmt.executeUpdate();
out.println("<html><body>");
out.println("Want to view the image?");
out.println("<a href=\"anything.viewimage\">Click here to get it!</a>");
out.println("</body></html>");
-->
Here is the snippet from the servlet that initiates the request for the image into the web browser:
<--
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
PrintWriter out = res.getWriter();
try {
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds = (DataSource)ctx.lookup(
"java:comp/env/jdbc/carsDB");
conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select pic from car");
while(rs.next()) {
FileOutputStream fo = new FileOutputStream("/images/theimage.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fo);
bos.write(rs.getBytes("pic"));
bos.close();
out.println("Here's the image");
out.println("<img src=\'/images/theimage.jpg'>");
}
}//try
-->
Folder structure looks like this:
jakarta-tomcat > myFolder > images
I do not have a lot of experience with BLOB's, as this is my first attempt to accomplish the insert and retrieval of images. I hope I've only made a simple error that will be easy to point out. If there is anything I haven't made clear or left out something pertinent...please let me know.
Any help or suggestions is appreciated,
Thank You,
Love2Java