If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > MySQL and JSP/Servlets vs THE BLOB!

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 09-14-03, 16:00
LordKrispy LordKrispy is offline
Registered User
 
Join Date: Sep 2003
Posts: 2
Arrow MySQL and JSP/Servlets vs THE BLOB!

Hello all,

I am having some issues with writing to a blob in a servlet. I have included the two key files: one that uploads to the database and the other that displays from the db to a browser. I would like to know if I am doing it correctly. It works intermitantly and I have already investigated possible memory issues ( i have my packet size set to 16M)
I am running Tomcat 4.1.26 and I am using MySql 4.0 and connecting using the provided JDBC drivers.

File 1: Display (NOTE THIS IS JAVA CODE)
-------------------------------------------------
package com.cg;

import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.sql.*;
import com.javaexchange.dbConnectionBroker.DbConnectionBr oker;

public class DisplayServlet extends HttpServlet {
private ServletContext myContext;
private ServletConfig myConfig;
DbConnectionBroker myBroker;


//Initialize global variables
public void init(ServletConfig config) throws ServletException {
System.out.print("Initializing Login Servlet...");
myConfig=config;
myContext=config.getServletContext();

// The below statement sets up a Broker with a minimun pool size of 2 connections
// and a maximum of 5. The log file will be created in
// D:\JavaWebServer1.1\DCB_Example.log and the pool connections will be
// restarted once a day.
try {myBroker = new DbConnectionBroker("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost/cg",
"root","",5,7,
"c:\\DCB_CG.log",0.01);
if(myBroker==null){
try{
this.log("Failed to connecto to database!");
}catch(Exception e){
System.out.println("Failed to connect to database!");
}

}
} catch (IOException e5) {
try{
this.log("Login Servlet: \n\tError 901\n\tBroker is null!\n\t"+e5);
}catch(Exception e){
System.out.println("Login Servlet: \n\tError 901\n\tBroker is null!\n\t"+e5);
}
}
System.out.println("Done.");
}

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{

res.setContentType("image/jpeg");
try {
String scr=req.getParameter("target");
String id=req.getParameter("id");
Connection con=null;
int attempts=10;
while(con==null){
con = myBroker.getConnection();
attempts--;
if(attempts==0){
System.out.println("Failed to establish connection for get pic!");
break;
}
}

if(con!=null){
Statement stmt = con.createStatement();
String query = "SELECT "+scr+" FROM photos WHERE accountID='"+id+"'";
ResultSet rs1 = stmt.executeQuery(query);
if (rs1.next()){
ServletOutputStream o= res.getOutputStream();
InputStream in=rs1.getBinaryStream(1);


byte[] bt = new byte [1000];
long re=1024;
for(int i = in.read(bt); re!= 0; )
{
re--;
o.write(bt);
in.read(bt);

}

in.close();
o.flush();
o.close();

}
con.close();
}else{
System.out.println("Connection could not be created for image display!");
}

}
catch (Exception e){
e.printStackTrace();
}

}
//Clean up resources
public void destroy() {
myBroker.destroy();
}

}


File 2: Upload (NOTE THIS IS A JAVA FILE)
-------------------------------------------------
package com.cg;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.javaexchange.dbConnectionBroker.DbConnectionBr oker;
import com.mysql.jdbc.Blob;
import com.oreilly.servlet.*;
import java.sql.*;


public class Upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
private ServletContext myContext;
private ServletConfig myConfig;
DbConnectionBroker myBroker;


//Initialize global variables
public void init(ServletConfig config) throws ServletException {
//super.init(config);
System.out.print("Initializing Upload Servlet...");
myConfig=config;
myContext=config.getServletContext();

// The below statement sets up a Broker with a minimun pool size of 2 connections
// and a maximum of 5. The log file will be created in
// D:\JavaWebServer1.1\DCB_Example.log and the pool connections will be
// restarted once a day.
try {myBroker = new DbConnectionBroker("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost/cg",
"root","",5,7,
"c:\\DCB_CG.log",0.01);
if(myBroker==null){
try{
this.log("Failed to connecto to database!");
}catch(Exception e){
System.out.println("Failed to connect to database!");
}

}
} catch (IOException e5) {
try{
this.log("Upload Servlet: \n\tError 901\n\tBroker is null!\n\t"+e5);
}catch(Exception e){
System.out.println("Upload Servlet: \n\tError 901\n\tBroker is null!\n\t"+e5);
}
}
System.out.println("Done.");

}

//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

com.oreilly.servlet.MultipartRequest multi = new com.oreilly.servlet.MultipartRequest(request, ".");
String target=multi.getParameter("target");
String id=multi.getParameter("id");
Enumeration files = multi.getFileNames();
if(files.hasMoreElements()){
String name = (String) files.nextElement();
String filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
java.io.File f = multi.getFile(name);
com.mysql.jdbc.Blob img=null;

try{
Connection c=myBroker.getConnection();
com.mysql.jdbc.PreparedStatement pstm=(com.mysql.jdbc.PreparedStatement)c.prepareSt atement(
"UPDATE photos SET "+target+" = ? WHERE accountID = ?");

Statement stm=c.createStatement();
String sql1="SELECT * FROM photos WHERE accountID='"+id+"'";
String sql2="update photos set active=1 where accountID='"+id+"'";
ResultSet rs=stm.executeQuery(sql1);
if(rs.next()){

img=(com.mysql.jdbc.Blob)rs.getBlob(target);
FileInputStream fsi = new FileInputStream(f);
//get ready to accept binary file
long i=1;
OutputStream out = img.setBinaryStream(i);
long chunk = f.length(); //.getChunkSize();
int ccrt=(int)chunk;
int seg=1024;
int crop=(int)(chunk/seg);
byte[] bt = new byte [ccrt];
long re=crop;
for(int ii = fsi.read(bt); re!= 0; )
{
re--;
out.write(bt);
fsi.read(bt);

}
System.out.println("Exit uploading pic. loop");
//in.close();
//out.flush();
//out.close();

//byte buffer[]= new byte[(int)chunk];
//int length;
//while ((length = fsi.read(buffer)) != -1)
// out.write(buffer, 0, length); //image file saved.

out.flush();
out.close();
fsi.close();
pstm.setBlob(1,img);
pstm.setString(2,id);
int ret=pstm.executeUpdate();
System.out.println("Fields affected: "+ret);
HashMap hm=new HashMap();
hm.put("photo","photosize");
hm.put("stage1","s1size");
hm.put("stage2","s2size");
hm.put("stage3","s3size");

String h=(String)hm.get(target);
ret=stm.executeUpdate("UPDATE photos SET "+h+"="+chunk+" WHERE accountID='"+id+"'");
System.out.println("Fields affected: "+ret);

}
rs.close();
stm.close();
myBroker.freeConnection(c);
}catch(Exception e){
System.out.println("Upload Image:\n\t"+e);
}

}



response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Upload</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a POST. This is the reply.</p>");
out.println("</body></html>");
}
//Clean up resources
public void destroy() {
}
}
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On