cofactor
asked on
save excel file into oracle DB as BLOB/CLOB
I have a jsp page.
it has a upload button.
user will upload an excel file.
excel file will be saved into the oracle database.
Question:
I am stuck at the last requirement i.e on the saving part into DB.
i am looking for a sample code to save the excel file directly into oracle DB ( CLOB/BLOB ?)?
can you help ?
it has a upload button.
user will upload an excel file.
excel file will be saved into the oracle database.
Question:
I am stuck at the last requirement i.e on the saving part into DB.
i am looking for a sample code to save the excel file directly into oracle DB ( CLOB/BLOB ?)?
can you help ?
u got any error or exception??
see this like for some sample progam to read and write BLOB data types
http://www.javangelist.de/space/JDBC/Blob
http://www.java2s.com/Code/Java/Database-SQL-JDBC/BlobJDBCdealswithBinaryData.htm
http://support.bea.com/application_content/product_portlets/support_patterns/wls/CLOBBLOBDataTypeHandlingIssuesPattern.html
http://www.javangelist.de/space/JDBC/Blob
http://www.java2s.com/Code/Java/Database-SQL-JDBC/BlobJDBCdealswithBinaryData.htm
http://support.bea.com/application_content/product_portlets/support_patterns/wls/CLOBBLOBDataTypeHandlingIssuesPattern.html
ASKER
Hi i saw http://www.javangelist.de/space/JDBC/Blob
they have code // for blob insertion
PreparedStatement statement = connection.prepareStatemen t(
"INSERT INTO MyTable (BlobColumn) VALUES (?)" );
File imageFile = new File( "myImage.jpg" ); // How do i get the real file name and location from the jsp ??
InputStream in = new FileInputStream( imageFile );
....................
....................
blah blah
How do i get the real file name and location from the client PC ??
i think , i need to write some code in the servlet to get the real file name and location of the uploaded file from the client PC....right ?
I dont know what to write .
Do i need to use third party package for this ?
they have code // for blob insertion
PreparedStatement statement = connection.prepareStatemen
"INSERT INTO MyTable (BlobColumn) VALUES (?)" );
File imageFile = new File( "myImage.jpg" ); // How do i get the real file name and location from the jsp ??
InputStream in = new FileInputStream( imageFile );
....................
....................
blah blah
How do i get the real file name and location from the client PC ??
i think , i need to write some code in the servlet to get the real file name and location of the uploaded file from the client PC....right ?
I dont know what to write .
Do i need to use third party package for this ?
Then you have to upload the file to the server and then try to put it in database.
Struts provides some utils for file upload see the below link
http://www.roseindia.net/struts/strutsfileupload.shtml
http://www.roseindia.net/struts/strutsfileuploadandsave.shtml
Struts provides some utils for file upload see the below link
http://www.roseindia.net/struts/strutsfileupload.shtml
http://www.roseindia.net/struts/strutsfileuploadandsave.shtml
In u r action class u can get the file content in bytes using this method as given in the example program
byte[] fileData = myFile.getFileData();
Then use ByteArrayInputStream to create a inputstream and set that one in statement
ByteArrayInputStream in = new ByteArrayInputStream(fileD ata);
statement.setBinaryStream( 1, // parameter index
in, // InputStream to read from
(int) fileData.length() // number of bytes to read
byte[] fileData = myFile.getFileData();
Then use ByteArrayInputStream to create a inputstream and set that one in statement
ByteArrayInputStream in = new ByteArrayInputStream(fileD
statement.setBinaryStream(
in, // InputStream to read from
(int) fileData.length() // number of bytes to read
ASKER
>Then you have to upload the file to the server and then try to put it in database
hmmm...ok...it looks fine but it would have been nicer if i could avoid uploading into server .
I would have been much more happier if i could DIRECTLY save the file to the Database ....because saving into server is of no use to me.
can i get that flexibility ?
is it impossible ? too complex ?
hmmm...ok...it looks fine but it would have been nicer if i could avoid uploading into server .
I would have been much more happier if i could DIRECTLY save the file to the Database ....because saving into server is of no use to me.
can i get that flexibility ?
is it impossible ? too complex ?
No actually we are not creating the file in the server side we are just transfering the content from the client to server and its stored in the server memory not stored in a file and from the memory we are creating InputStream and storing the content into the database. So nowhere we are storing the file.
ASKER
ok.
thats fine then .
but you have a struts file upload example.
i have only jsp and servlet ...no struts .
so, myFile in your code ...is formbean i think which does not exist in my case.
Anyway,
here is my jsp snippet
<tr>
<td width="20%" colspan="2">Browse file</td>
<td width="50%" colspan="1">
<input type="file" name="file" id="file"/>
</td>
<td width="30%" colspan="1"></td>
</tr>
<tr>
<td width="20%" colspan="2">Upload file</td>
<td width="50%" colspan="1">
<input type="Submit" value="Upload"/>
</td>
<td width="30%" colspan="1"></td>
</tr>
from here , can you please tell me what should i write in my servlet code to get the filename and real path ?
I am not using struts.
thats fine then .
but you have a struts file upload example.
i have only jsp and servlet ...no struts .
so, myFile in your code ...is formbean i think which does not exist in my case.
Anyway,
here is my jsp snippet
<tr>
<td width="20%" colspan="2">Browse file</td>
<td width="50%" colspan="1">
<input type="file" name="file" id="file"/>
</td>
<td width="30%" colspan="1"></td>
</tr>
<tr>
<td width="20%" colspan="2">Upload file</td>
<td width="50%" colspan="1">
<input type="Submit" value="Upload"/>
</td>
<td width="30%" colspan="1"></td>
</tr>
from here , can you please tell me what should i write in my servlet code to get the filename and real path ?
I am not using struts.
http://cit3.cdn.swin.edu.au/utilities/upload/File_Upload_Using_Java.html --- very simple just using servlet with out any other library
You can use Apache file upload to make u r job easy you can download it from
http://commons.apache.org/fileupload/
and some example on it
http://www.geekinterview.com/question_details/17234
http://commons.apache.org/fileupload/using.html
You can use Apache file upload to make u r job easy you can download it from
http://commons.apache.org/fileupload/
and some example on it
http://www.geekinterview.com/question_details/17234
http://commons.apache.org/fileupload/using.html
ASKER
Ok.
i saw http://www.geekinterview.com/question_details/17234
and i copied this code from there...
public class UploadFile extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res)
{
try{
FileUpload fup=new FileUpload();
boolean isMultipart = FileUpload.isMultipartCont ent(req);
// Create a new file upload handler
System.out.println(isMulti part);
DiskFileUpload upload = new DiskFileUpload();
// Parse the request
List /* FileItem */ items = upload.parseRequest(req);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
System.out.println("its a field");
} else {
System.out.println("its a file");
System.out.println(item.ge tName());
File cfile=new File(item.getName()); // got it
Now , i have got the File object from the client in memory and from here i can plug this into our old blob code
like this way ....
InputStream in = new FileInputStream( cfile ); // plugged cfile here
statement.setBinaryStream(
1, // parameter index
in, // InputStream to read from
(int) imageFile.length() // number of bytes to read
);
statement.executeUpdate();
please comment on this .
is this ok ?
i saw http://www.geekinterview.com/question_details/17234
and i copied this code from there...
public class UploadFile extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res)
{
try{
FileUpload fup=new FileUpload();
boolean isMultipart = FileUpload.isMultipartCont
// Create a new file upload handler
System.out.println(isMulti
DiskFileUpload upload = new DiskFileUpload();
// Parse the request
List /* FileItem */ items = upload.parseRequest(req);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
System.out.println("its a field");
} else {
System.out.println("its a file");
System.out.println(item.ge
File cfile=new File(item.getName()); // got it
Now , i have got the File object from the client in memory and from here i can plug this into our old blob code
like this way ....
InputStream in = new FileInputStream( cfile ); // plugged cfile here
statement.setBinaryStream(
1, // parameter index
in, // InputStream to read from
(int) imageFile.length() // number of bytes to read
);
statement.executeUpdate();
please comment on this .
is this ok ?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
FileUpload fup=new FileUpload();
boolean isMultipart = FileUpload.isMultipartCont ent(reques t);
System.out.println("isMult ipart"+isM ultipart); // it prints true
DiskFileUpload upload = new DiskFileUpload();
System.out.println("upload "+upload); // it prints uploadorg.apache.commons.f ileupload. DiskFileUp load@705e6 9
List /* FileItem */ items = upload.parseRequest(reques t);
System.out.println("items" +items); // no other print from here !!!! ....LINE-1
Iterator iter = items.iterator();
System.out.println("iter"+ iter);
while (iter.hasNext()) {
System.out.println("i");
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
System.out.println("its a field");
} else {
System.out.println("its a file");
System.out.println(item.ge tName());
File cfile=new File(item.getName());
System.out.println("its a file"+cfile);
Connection con=(new DBUtil()).getConnection();
//Statement stmt=con.createStatement() ;
i am not getting any prints from .LINE-1
can you please tell whats wrong there ?
boolean isMultipart = FileUpload.isMultipartCont
System.out.println("isMult
DiskFileUpload upload = new DiskFileUpload();
System.out.println("upload
List /* FileItem */ items = upload.parseRequest(reques
System.out.println("items"
Iterator iter = items.iterator();
System.out.println("iter"+
while (iter.hasNext()) {
System.out.println("i");
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
System.out.println("its a field");
} else {
System.out.println("its a file");
System.out.println(item.ge
File cfile=new File(item.getName());
System.out.println("its a file"+cfile);
Connection con=(new DBUtil()).getConnection();
//Statement stmt=con.createStatement()
i am not getting any prints from .LINE-1
can you please tell whats wrong there ?
Chek the items size
ASKER
ok, printed the size ....but no print coming :(
System.out.println("isMult ipart"+isM ultipart);
DiskFileUpload upload = new DiskFileUpload();
System.out.println("upload "+upload);
// Parse the request
List /* FileItem */ items = upload.parseRequest(reques t);
System.out.println("size of items"+items.size());
System.out.println("items" +items);
Iterator iter = items.iterator();
System.out.println("iter"+ iter);
console output:
isMultiparttrue
uploadorg.apache.commons.f ileupload. DiskFileUp load@253cd e
System.out.println("isMult
DiskFileUpload upload = new DiskFileUpload();
System.out.println("upload
// Parse the request
List /* FileItem */ items = upload.parseRequest(reques
System.out.println("size of items"+items.size());
System.out.println("items"
Iterator iter = items.iterator();
System.out.println("iter"+
console output:
isMultiparttrue
uploadorg.apache.commons.f
ASKER
is it because of DiskFileUpload() and parseRequest method deprecated ? because myeclipse editor is saying these are deprecated.
However, i dont believe that it could be the cause ....at least i could get some print anyhow .
i am building and deploying freshly everytime .
However, i dont believe that it could be the cause ....at least i could get some print anyhow .
i am building and deploying freshly everytime .
ASKER
and also there is no exception in the console !
everything is hushed up :(
everything is hushed up :(
u enclosed every thing inside try catch block if ur then in the catch block try to print the stacktrace. And also u can degug and see in the Eclipse IDE so that u can know where its going worng
ASKER
did the debug mode
the trouble some area is
List /* FileItem */ items = upload.parseRequest(reques t); ----> control goes out from here.
investigating whats wrong here .
if u have any input here plz tell, will look into that too.
the trouble some area is
List /* FileItem */ items = upload.parseRequest(reques
investigating whats wrong here .
if u have any input here plz tell, will look into that too.
ASKER
some more update.....
though i already have a try-catch bolck wrapped in my code already
.....................
........................
}catch(Exception e){System.out.println(e);} // but this catch is not catching and printing exception .
i think , its a different kind of exception...something servlet invokation exception .
not sure ...still investigating more...
though i already have a try-catch bolck wrapped in my code already
.....................
........................
}catch(Exception e){System.out.println(e);}
i think , its a different kind of exception...something servlet invokation exception .
not sure ...still investigating more...
ASKER
I got
List /* FileItem */ items = upload.parseRequest(reques t);
is throwing :
An exception occured java.lang.NoClassDefFoundE rror
what to do now :(
List /* FileItem */ items = upload.parseRequest(reques
is throwing :
An exception occured java.lang.NoClassDefFoundE
what to do now :(
which calss clauses the exception after the exception u have the Class name like this
java.lang.NoClassDefFoundE rror "Class name"
java.lang.NoClassDefFoundE
ASKER
somehow i am not getting that class.
here is the screenshot you can see
http://img252.imageshack.us/img252/5462/testqz8.png
here is the screenshot you can see
http://img252.imageshack.us/img252/5462/testqz8.png
i cant see the image send to my email pradeepd12@gmail.com
ASKER
finally got it
java.lang.NoClassDefFoundE rror: org/apache/commons/io/File Cleaner
at org.apache.commons.fileupl oad.disk.D iskFileIte m.getTempF ile(DiskFi leItem.jav a:600)
at org.apache.commons.fileupl oad.disk.D iskFileIte m.getOutpu tStream(Di skFileItem .java:540)
at org.apache.commons.fileupl oad.FileUp loadBase.p arseReques t(FileUplo adBase.jav a:354)
at org.apache.commons.fileupl oad.FileUp loadBase.p arseReques t(FileUplo adBase.jav a:302)
at com.pwc.controller.ExcelUp loadServle t.doPost(E xcelUpload Servlet.ja va:106)
at javax.servlet.http.HttpSer vlet.servi ce(HttpSer vlet.java: 760)
at javax.servlet.http.HttpSer vlet.servi ce(HttpSer vlet.java: 853)
at weblogic.servlet.internal. ServletStu bImpl$Serv letInvocat ionAction. run(Servle tStubImpl. java:1072)
at weblogic.servlet.internal. ServletStu bImpl.invo keServlet( ServletStu bImpl.java :465)
at weblogic.servlet.internal. ServletStu bImpl.invo keServlet( ServletStu bImpl.java :348)
at weblogic.servlet.internal. WebAppServ letContext $ServletIn vocationAc tion.run(W ebAppServl etContext. java:6981)
at weblogic.security.acl.inte rnal.Authe nticatedSu bject.doAs (Authentic atedSubjec t.java:321 )
at weblogic.security.service. SecurityMa nager.runA s(Security Manager.ja va:121)
at weblogic.servlet.internal. WebAppServ letContext .invokeSer vlet(WebAp pServletCo ntext.java :3892)
at weblogic.servlet.internal. ServletReq uestImpl.e xecute(Ser vletReques tImpl.java :2766)
at weblogic.kernel.ExecuteThr ead.execut e(ExecuteT hread.java :224)
at weblogic.kernel.ExecuteThr ead.run(Ex ecuteThrea d.java:183 )
org.apache.commons.fileupl oad.FileUp loadExcept ion: Connection reset
any suggestion now :(
i have the latest commons upload jar 1.2
i cant believe that its a faulty one :(
java.lang.NoClassDefFoundE
at org.apache.commons.fileupl
at org.apache.commons.fileupl
at org.apache.commons.fileupl
at org.apache.commons.fileupl
at com.pwc.controller.ExcelUp
at javax.servlet.http.HttpSer
at javax.servlet.http.HttpSer
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.security.acl.inte
at weblogic.security.service.
at weblogic.servlet.internal.
at weblogic.servlet.internal.
at weblogic.kernel.ExecuteThr
at weblogic.kernel.ExecuteThr
org.apache.commons.fileupl
any suggestion now :(
i have the latest commons upload jar 1.2
i cant believe that its a faulty one :(
ASKER
dont worry about the image ....i just printed that exception in the console ...so please take that .
See this forum
http://www.velocityreviews.com/forums/t151220-apache-fileupload-javalangnoclassdeffounderror-orgapachecommonsiofilecleaner.html
check all the dependency
http://www.velocityreviews.com/forums/t151220-apache-fileupload-javalangnoclassdeffounderror-orgapachecommonsiofilecleaner.html
check all the dependency
download the Commons IO here
http://commons.apache.org/io/
File Cleaner class found in that CommonsIO API
http://commons.apache.org/io/apidocs/org/apache/commons/io/FileCleaner.html
http://commons.apache.org/io/
File Cleaner class found in that CommonsIO API
http://commons.apache.org/io/apidocs/org/apache/commons/io/FileCleaner.html
ASKER
yes...you are amazing man.
it worked like a charm.
data is going into database perfectly.
you are excellent .
one more question
in fact when my user clicks on a link ( i am providing an id from the DB's BLOB ) , he would be able to download that excel file . he must get a download prompt.
can you please provide some example code .
I am increasing point.
it worked like a charm.
data is going into database perfectly.
you are excellent .
one more question
in fact when my user clicks on a link ( i am providing an id from the DB's BLOB ) , he would be able to download that excel file . he must get a download prompt.
can you please provide some example code .
I am increasing point.
ASKER
i want to give a download prompt to the user .
as u know i have BLOB data in DB .
so , how does this BLOB data will give a download prompt so that user can download the excel file when they click on a download link ?
as u know i have BLOB data in DB .
so , how does this BLOB data will give a download prompt so that user can download the excel file when they click on a download link ?
for info see this link
http://ibphoenix.com/main.nfs?page=ibp_iclient_blob
after getting the data in byte array in the servlet output stream write all the byte content and you need to set the content-type and some other headers like this
res.setContentType("applic ation/x-do wnload");
res.setHeader("Content-Dis position", "attachment; filename=" + filename);
for more info see this link
http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index3.html
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=7&t=016177
http://ibphoenix.com/main.nfs?page=ibp_iclient_blob
after getting the data in byte array in the servlet output stream write all the byte content and you need to set the content-type and some other headers like this
res.setContentType("applic
res.setHeader("Content-Dis
for more info see this link
http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index3.html
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=7&t=016177
public byte[] selectBlob( int rowid ) {
// In this example I'm assuming there's an open, active
// Connection instance called 'con'.
// This examples uses an imaginary SQL table of the following
// form:
//
// CREATE TABLE blobs (
// ROWID INT NOT NULL,
// ROWDATA BLOB,
//
// PRIMARY KEY (rowid)
// );
try {
Statement sment = con.createStatement();
String sql = "SELECT rowid, rowdata FROM blobs WHERE rowid = " + rowid;
ResultSet rs = sment.executeQuery(sql);
byte[] returndata = null;
if ( rs.next() ) {
try {
// The ByteArrayOutputStream buffers all bytes written to it
// until we call getBytes() which returns to us an array of bytes:
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
// Create an input stream from the BLOB column. By default, rs.getBinaryStream()
// returns a vanilla InputStream instance. We override this for efficiency
// but you don't have to:
BufferedInputStream bis = new BufferedInputStream( rs.getBinaryStream("fieldblob") );
// A temporary buffer for the byte data:
byte bindata[1024];
// Used to return how many bytes are read with each read() of the input stream:
int bytesread = 0;
// Make sure its not a NULL value in the column:
if ( !rs.wasNull() ) {
if ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 ) {
// Write out 'bytesread' bytes to the writer instance:
baos.write(bindata,0,bytesread);
} else {
// When the read() method returns -1 we've hit the end of the stream,
// so now we can get our bytes out of the writer object:
returndata = baos.getBytes();
}
}
// Close the binary input stream:
bis.close();
} catch ( IOException ioe ) {
System.err.println("Problem retrieving binary data: " + ioe);
} catch ( ClassNotFoundException cnfe ) {
System.err.println("Problem retrieving binary data: " + cnfe);
}
}
rs.close();
sment.close();
} catch ( SQLException se ) {
System.err.println("Couldn't retrieve binary data: " + se);
} finally {
con.close();
}
return returndata;
}
ASKER
thanks for the example code.
i dont understand why MyEclipse is saying
byte bindata[1024]; // syntax error on token 1024 ... delete this token .
any idea ?
i dont understand why MyEclipse is saying
byte bindata[1024]; // syntax error on token 1024 ... delete this token .
any idea ?
ASKER
modified that line to
byte bindata[]=new byte[1024];
byte bindata[]=new byte[1024];
If u dont have any questions accept my answer
ASKER
yea...deeppra ....your answer is almost perfect .
i am just testing download code.
somehow , i am not able to call the servlet .
so, not able to test .
will close this question very soon.
i am just testing download code.
somehow , i am not able to call the servlet .
so, not able to test .
will close this question very soon.
ASKER
i am sending id and filename to the servlet from the jsp link.
you can look here about the problem i am facing
https://www.experts-exchange.com/questions/22978564/url-not-working.html
i will close this question as soon as i can test it .
thanks
you can look here about the problem i am facing
https://www.experts-exchange.com/questions/22978564/url-not-working.html
i will close this question as soon as i can test it .
thanks
yea sure
ASKER
closing question.
it was helpful.
it was helpful.
ASKER