How to store file content in BLOB field MySql database using java
Hi!
i want to store the file content in a BLOB field in MySql database using java.
Please help me out..........
thanx in advance...
bye
i stored images in db, and retrieved them. like that cant i store pdf file in db, and retrieve it back using oracle db?
Plz help me out how to put a file in db. i need complete code. thanks in advance.
Similar Messages
-
How to save file content in BLOB using ODI?
We have unix server where the files are stored in a particular directory.
I have to create one table in Oracle db which will have 2columns.
One column will have filename & in another column i need to store file content(whatever that file has) which should be a BLOB type.
There is no restriction on file type,it could be .txt,.xls,.jpg.
Need help
Edited by: user11090018 on Jun 9, 2010 4:24 AM
Edited by: user11090018 on Jun 10, 2010 10:22 PMIf you can give a detail explanation about your requirement then we may try to come up with a solution .....
-
How to store file content in database??????
how to store file in database and retrived
How to use Google to search for answers to questions that have been asked literally thousands of times previously??????
How to post into the correct forum???????
How to use less punctuation?????? -
How to Convert the content in BLOB field into a PDF file...
Hi,
I am having PDF files stored in BLOB column of a table in Oracle Database (11G R2).
I want to retrieve the files back and store them in hard disk. I am successful in storing the content as a file with '.doc' but if I store the file as '.pdf', adobe fails to open the file with error
Adobe Reader could not open file 'xxx.pdf' because it is either not a supported file type or because the file has been damaged (for example it was sent as an email attachment and wasn't correctly decoded)
I am using following example code to achieve my goal...
Declare
b blob;
c clob;
buffer VARCHAR2(32767);
buffer_size CONSTANT BINARY_INTEGER := 32767;
amount BINARY_INTEGER;
offset NUMBER(38);
file_handle UTL_FILE.FILE_TYPE;
begin
select blob_data into b from blobdata where id=1;
c := blob2clob(b);
file_handle := UTL_FILE.FOPEN('BLOB2FILE','my_file.pdf','w',buffer_size);
amount := buffer_size;
offset := 1;
WHILE amount >= buffer_size
LOOP
DBMS_LOB.READ(c,amount,offset,buffer);
-- buffer:=replace(buffer,chr(13),'');
offset := offset + amount;
UTL_FILE.PUT(file_handle,buffer);
UTL_FILE.FFLUSH(file_handle);
END LOOP;
UTL_FILE.FCLOSE(file_handle);
end;
create or replace FUNCTION BLOB2CLOB ( p_blob IN BLOB ) RETURN CLOB
-- typecasts BLOB to CLOB (binary conversion)
IS
|| Purpose : To Convert a BLOB File to CLOB File
|| INPUT : BLOB File
|| OUTPUT : CLOB File
|| History: MB V5.0 24.09.2007 RCMS00318572 Initial version
ln_file_check NUMBER;
ln_file_size NUMBER;
v_text_file CLOB;
v_binary_file BLOB;
v_dest_offset INTEGER := 1;
v_src_offset INTEGER := 1;
v_warning INTEGER;
lv_data CLOB;
ln_length NUMBER;
csid VARCHAR2(100) := DBMS_LOB.DEFAULT_CSID;
V_LANG_CONTEXT NUMBER := DBMS_LOB.DEFAULT_LANG_CTX;
BEGIN
DBMS_LOB.createtemporary (v_text_file, TRUE);
SELECT dbms_lob.getlength(p_blob) INTO ln_file_size FROM DUAL;
DBMS_LOB.converttoclob (v_text_file, p_blob, ln_file_size, v_dest_offset, v_src_offset, 0, v_lang_context, v_warning);
SELECT dbms_lob.getlength(v_text_file) INTO ln_length FROM DUAL;
RETURN v_text_file;
END;user755667 wrote:
Hi,
I am having PDF files stored in BLOB column of a table in Oracle Database (11G R2).
I want to retrieve the files back and store them in hard disk. I am successful in storing the content as a file with '.doc' but if I store the file as '.pdf', adobe fails to open the file with error
Adobe Reader could not open file 'xxx.pdf' because it is either not a supported file type or because the file has been damaged (for example it was sent as an email attachment and wasn't correctly decoded)
I am using following example code to achieve my goal...
Declare
b blob;
c clob;
buffer VARCHAR2(32767);
buffer_size CONSTANT BINARY_INTEGER := 32767;
amount BINARY_INTEGER;
offset NUMBER(38);
file_handle UTL_FILE.FILE_TYPE;
begin
select blob_data into b from blobdata where id=1;
c := blob2clob(b);
file_handle := UTL_FILE.FOPEN('BLOB2FILE','my_file.pdf','w',buffer_size);
amount := buffer_size;
offset := 1;
WHILE amount >= buffer_size
LOOP
DBMS_LOB.READ(c,amount,offset,buffer);
-- buffer:=replace(buffer,chr(13),'');
offset := offset + amount;
UTL_FILE.PUT(file_handle,buffer);
UTL_FILE.FFLUSH(file_handle);
END LOOP;
UTL_FILE.FCLOSE(file_handle);
end;
create or replace FUNCTION BLOB2CLOB ( p_blob IN BLOB ) RETURN CLOB
-- typecasts BLOB to CLOB (binary conversion)
IS
|| Purpose : To Convert a BLOB File to CLOB File
|| INPUT : BLOB File
|| OUTPUT : CLOB File
|| History: MB V5.0 24.09.2007 RCMS00318572 Initial version
ln_file_check NUMBER;
ln_file_size NUMBER;
v_text_file CLOB;
v_binary_file BLOB;
v_dest_offset INTEGER := 1;
v_src_offset INTEGER := 1;
v_warning INTEGER;
lv_data CLOB;
ln_length NUMBER;
csid VARCHAR2(100) := DBMS_LOB.DEFAULT_CSID;
V_LANG_CONTEXT NUMBER := DBMS_LOB.DEFAULT_LANG_CTX;
BEGIN
DBMS_LOB.createtemporary (v_text_file, TRUE);
SELECT dbms_lob.getlength(p_blob) INTO ln_file_size FROM DUAL;
DBMS_LOB.converttoclob (v_text_file, p_blob, ln_file_size, v_dest_offset, v_src_offset, 0, v_lang_context, v_warning);
SELECT dbms_lob.getlength(v_text_file) INTO ln_length FROM DUAL;
RETURN v_text_file;
END;I skimmed this and stopped reading when i saw the BLOB to CLOB function.
You can't convert binary data into character based data.
So very likely this is your problem. -
How to store images in BLOB field in MySql database using java
Hi....
Currently am able to store character string into BLOB using byte array....in MySql.
but i cannot store images or pictures.......
to do this.........please help me out...............
Thanx..........:)Bye...........Hello,
I have done this for Oracle but it should be similar in MySQL also. Try reading thru these links below. Mail us if you have succeeded or not.
http://forum.java.sun.com/thread.jspa?forumID=48&threadID=654086
http://forum.java.sun.com/thread.jspa?forumID=48&threadID=384768
http://forum.java.sun.com/thread.jspa?forumID=48&threadID=549705
Thanks and regards,
Pazhanikanthan. P -
How to verify if user already exists in MySQL database using JSP?
Hi, I am trying to create a website that allows users to register and then login. All regsitration details are stored in a MySQL table and I am attempting to have a java bean check that a new user does not already exist by looking up the username. However, I cannot get this to work, the bean is allowing anyone through. I believe there may be a problem with my while loop as the bean checks through the stored usernames in the database. Any suggestions appreciated thanks. See my code below:[
code]package foo;
import java.sql.*;
import java.util.*;
public class FormBean {
private String firstName;
private String lastName;
private String email;
private String userName;
private String password1;
private String password2;
private Hashtable errors;
public boolean validate() {
boolean allOk=true;
if (firstName.equals("")) {
errors.put("firstName","Please enter your first name");
firstName="";
allOk=false;
if (lastName.equals("")) {
errors.put("lastName","Please enter your last name");
lastName="";
allOk=false;
if (email.equals("") || (email.indexOf('@') == -1)) {
errors.put("email","Please enter a valid email address");
email="";
allOk=false;
if (userName.equals("")) {
errors.put("userName","Please enter a username");
userName="";
allOk=false;
try {
String database = "******hidden******";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(database,"********hidden*******");
Statement stat = conn.createStatement();
String query="SELECT u_name FROM users;";
String DbUserName="";
ResultSet rst=stat.executeQuery(query);
while(rst.next()) {
DbUserName=rst.getString("u_name");
if (userName.equals(DbUserName)) {
allOk=false;
errors.put("userName","User name already exists, please choose another");
userName="";
conn.close();
break;
} catch (Exception ex) {
ex.printStackTrace();
if (password1.equals("") ) {
errors.put("password1","Please enter a valid password");
password1="";
allOk=false;
if (!password1.equals("") && (password2.equals("") || !password1.equals(password2))) {
errors.put("password2","Please confirm your password");
password2="";
allOk=false;
return allOk;
public String getErrorMsg(String s) {
String errorMsg =(String)errors.get(s.trim());
return (errorMsg == null) ? "":errorMsg;
public FormBean() {
firstName="";
lastName="";
email="";
userName="";
password1="";
password2="";
errors = new Hashtable();
public String getFirstName() {
return firstName;
public String getLastName() {
return lastName;
public String getEmail() {
return email;
public String getUserName() {
return userName;
public String getPassword1() {
return password1;
public String getPassword2() {
return password2;
public void setFirstName(String fname) {
firstName =fname;
public void setLastName(String lname) {
lastName =lname;
public void setEmail(String eml) {
email=eml;
public void setUserName(String u) {
userName=u;
public void setPassword1(String p1) {
password1=p1;
public void setPassword2(String p2) {
password2=p2;
public void setErrors(String key, String msg) {
errors.put(key,msg);Hmm, tried that and now have more build errors in the finally section.
init:
deps-jar:
Compiling 1 source file to C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\build\classes
C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:57: cannot resolve symbol
symbol : variable rst
location: class foo.FormBean
if (rst != null) rst.close();
C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:57: cannot resolve symbol
symbol : variable rst
location: class foo.FormBean
if (rst != null) rst.close();
C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:58: cannot resolve symbol
symbol : variable stat
location: class foo.FormBean
if (stat != null) stat.close();
C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:58: cannot resolve symbol
symbol : variable stat
location: class foo.FormBean
if (stat != null) stat.close();
C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:59: cannot resolve symbol
symbol : variable conn
location: class foo.FormBean
if (conn != null) conn.close();
C:\resin-2.1.11\doc\examples\basic\WEB-INF\classes\JavaLibrary1\test\FormBean.java:59: cannot resolve symbol
symbol : variable conn
location: class foo.FormBean
if (con != null) conn.close();
6 errors
BUILD FAILED (total time: 1 second)Just for a quick test, I deleted the sql exception and finally code and replaced it with a regular exception just to see what happened and got no build errors, however when I run the form I am getting an sql exception from the prepared statement, parameter out of range (1 > 0). I tried reading into prepared statements, and although I now understand their basics, I still have no idea why I'm getting this error? -
How do you query Oracle RDF database using Java program?
Does anyone know how to get data out of the oracle RDF database using Java?
I'm running the following java code and it returns basically null values. My guess is that the get_triple() function returns a dataset other than resultset. I've tried searching the Oracle web site. Am I supposed to be using CLOB object? Any help would be appreciated. Thanks
sql = "SELECT a.triple.GET_TRIPLE() AS triple FROM family_rdf_data a";
ResultSet rs = stmt.executeQuery( sql ) ;
while ( rs.next() )
System.out.println( rs.getString(1) ) ;
rs.close() ;get_triple() returns an object, and the code would be different from the code of retrieving a string. Some sample code for retrieving objects is at http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/advanced/advanced.html
get_subject(), get_property() return strings so the code below should work. get_object() returns a CLOB so different handling would be required and there is some sample code at the link above.
Melli -
How to store the contents of a file
Hi,
I'm using forms6i and database 10g.
Through forms if a user selects a filename , and clicks a button or something,
the contents of the file should be saved in the database.
The file can be of any type, like .doc,.pdf,.xml,.html etc...
and the contents filed will be of type varchar
Please help me do this..
ThanksDo you really want to save the "Content" of a file or the file itself? If you try to save the contents of a .doc or .pdf in a column with a VARCHAR2 datatype, you are going to corrupt the contents of the file since these file types have binary data in them as well as text. I think you would have greater success storing the actual file in a BLOB column.
Here are a few Oracle Support documents that discuss how to store and retrieve files stored as BLOBs in the database.
Doc ID: 168277.1 - How to Upload Binary Documents Back to Database BLOB Column from Forms
Doc ID: 330146.1 - How to write BLOBs Stored Inside the Database Out to Files.
Hope this helps,
Craig B-)
If someone's response is helpful or correct, please mark it accordingly. -
How To Store pdf or doc file in Oracle Database using Java Jdbc?
can any one help me out How To Store pdf or doc file in Oracle Database using Java Jdbc in JSP/Serlet? i tried like anything. using blob also i tried. but i am able 2 store images in DB not files. please if u know or else if u have some code like this plz send that to me, and help me out plz. i need that urgent.
Hi.. i am not getting error, But i am not getting the original contents from my file. i am getting all ASCII vales, instead of my original data. here i am including my code.
for Adding PDF in DB i used image.jsp
Database table structure (table name. pictures )
Name Null? Type
ID NOT NULL NUMBER(11)
IMAGE BLOB
<%@ page language="java" import="java.util.*,java.sql.*,java.io.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
PreparedStatement ps,pstmt,psmnt;
ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
File file =
new File("D:/info.pdf");
FileInputStream fs = new FileInputStream(file);
ps.setInt(1,4);
ps.setBinaryStream(2,fs,fs.available());
int i = ps.executeUpdate();
if(i!=0){
out.println("<h2>PDF inserted successfully");
else{
out.println("<h2>Problem in image insertion");
catch(Exception e){
out.println("<h2>Failed Due To "+e);
%>
O/P: PDF inserted successfully
i tried to display that pdf using servlet. i am giving the code below.
import java.io.IOException;
import java.sql.*;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DispPDF extends HttpServlet {
* The doGet method of the servlet. <br>
* This method is called when a form has its tag value method equals to get.
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html"); i commented. coz we cant use response two times.
//PrintWriter out = response.getWriter();
try{
InputStream sPdf;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.135:1521:orcl","scott","tiger");
PreparedStatement ps,pstmt,psmnt;
psmnt = con.prepareStatement("SELECT image FROM pictures WHERE id = ?");
psmnt.setString(1, "4"); // here integer number '4' is image id from the table.
ResultSet rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
//out.println(bytearray);
int size=0;
sPdf = rs.getBinaryStream(1);
response.reset();
response.setContentType("application/pdf");
while((size=sPdf.read(bytearray))!= -1 ){
//out.println(size);
response.getOutputStream().write(bytearray,0,size);
catch(Exception e){
System.out.println("Failed Due To "+e);
//out.println("<h2>Failed Due To "+e);
//out.close();
OP
PDF-1.4 %âãÏÓ 2 0 obj <>stream x+är á26S°00SIá2PÐ5´1ôÝ BÒ¸4Ü2KüsSSS4C²ê Pkø$VãGÒU×713CkW )(Ü endstream endobj 4 0 obj <>>>/MediaBox[0 0 595 842]>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000325 00000 n 0000000015 00000 n 0000000413 00000 n 0000000168 00000 n 0000000464 00000 n 0000000509 00000 n trailer <<01b2fa8b70ac262bfa939cc786f8770c>]/Root 5 0 R/Size 7/Info 6 0 R>> startxref 641 %%EOF
plz help me out. -
Storing a file in a BLOB field in the database through forms
Hi, I want to have a form that lets the user choose a file he has on his client side and load this file into a BLOB field in the database.
I know how to use "GET_FILE_NAME" to get the file, the second part is what I'm having problems with. Do I use an OLE object? How do I initailize it? Or what is the best way to go? Thanks.
--BassemAre you looking for something like this?
DECLARE
l_temp clob;
l_text varchar2(2000);
BEGIN
l_temp := httpuritype('http://www.oracle.com/PO.xsd').getclob;
l_text := substr(l_temp, 1, 2000);
dbms_output.put_line(l_text);
END;N.B.: Not Tested...
Regards.
Satyaki De. -
Hi,
I have a problem to transfer a XML file content to a MS SQL database by a given/fixed stored procedure. I'm able to transfer the content of the file by using following method ...
hstmt = DBPrepareSQL (hdbc, EXEC usp_InsertReport '<Report> ..... </Report>');
resCode = DBExecutePreparedSQL (hstmt);
resCode = DBClosePreparedSQL (hstmt);
... but in this case I'm not able to fetch the return value of the stored procedure!
I have tried to follow the example of the stored procedure in the help documentation (DBPrepareSQL) but I miss a datatype for xml?!?
Any idea how to solve my problem?
KR Cake
Solved!
Go to Solution.After some additional trials I found a solution by calling the stored procedure in this way
DBSetAttributeDefault (hdbc, ATTR_DB_COMMAND_TYPE, DB_COMMAND_STORED_PROC);
DBPrepareSQL (hdbc, "usp_InsertReport");
DBCreateParamInt (hstmt, "", DB_PARAM_RETURN_VALUE, -1);
DBCreateParamChar (hstmt, "XMLCONTENT", DB_PARAM_INPUT, sz_Buffer, (int) strlen(sz_Buffer) + 1 );
DBExecutePreparedSQL (hstmt);
DBClosePreparedSQL (hstmt);
DBGetParamInt (hstmt, 1, &s32_TestId);
where sz_Buffer is my xml file content and s32_TestID the return value of the stored procdure (usp_InsertReport(@XMLCONTENT XML))
Now I face the problem, that DBCreateParamChar limits the buffer size to 8000 Bytes.
Any idea to by-pass this shortage?? -
How To Store Files On a Server?
I am using the Tomcat 5.0.27 web container. I have always store things into the database. Now, I am told to store files (uploaded files) on the server. And, when clients want the files later on, clients can download them.
Because I have not yet had this concept, I need help and explanation.
1. How to store files on a server?
2. Where on the server that files can be stored?
3. How to let clients download files when they are asked to be viewed?Look at the Jakarta Commons FileUpload package.
-
How to display and save a picture stored as BLOB in MySQL database in Jsp?
Hello i am doing a dataentry form where in i will display the picture stored as Blob in MySQL database to the browser. The form also allow changing the picture and updating the picture Blob in the database.
How can i do it? I try this
<img src'"<%=rs.getBlob("picture")%> but it doesn't display the picture.
another thing, how can i save it in the database, if is use the file field in the html form?
thanks in advance for your help.Hello i am doing a dataentry form where in i will display the picture stored as Blob in MySQL database to the browser. The form also allow changing the picture and updating the picture Blob in the database.
How can i do it? I try this
<img src'"<%=rs.getBlob("picture")%> but it doesn't display the picture.
another thing, how can i save it in the database, if is use the file field in the html form?
thanks in advance for your help. -
Uploading the file as a blob to oracle database
Hi..I wrote a program to upload the files as a blob to the database. It works fine for JSP files but when i try to upload a css file...it gives "No more data to read from socket" exception. I have tried all combinations like trying to upload css file first and then a jsp file and then multiple jsp file and then a css file and so on, thinking that it might be a storage problem. But it gives an error only for the css files...could there be any delimiter kind of symbol or something in the css file which make the oracle think that it is the end of file? Just a guess...any help is appreciated...
n btw i upload the file using the file input stream and then i use preparedStatement.setBinaryStream method ....
TIADamn it...I cant believe that i took this long to figure it out...the maximum size of the file that my blob can store is 4 kb...and all my css files are bigger than that...wasted so many hours on this...:(
-
How to store images in database using java
hii
how to store images in database using java..........
Message was edited by:
naveennagaI asked a similar question once and the answer I got was - Don't.
Instead, store the images on a drive somewhere and store the path in the database.
But I'm no expert - that's just what I was told by someone who does this kind of stuff a lot.
Hope that helps.
Maybe you are looking for
-
Iphone 4 problem with car connection.
Hey, I have been using an xcarlink ipod adapter in my 2006 Mazda six since about December and up to a few days ago it was working perfectly fine. Now whenever I plug my iphone 4 in I am no longer able to browse my songs on it, instead all it says now
-
Safari 3.1 Install - Breaks Mail, Update Manager, Help, Safari
I downloaded and installed Safari 3.1. Afterwords, all apps that use webkit appear to be broken. They attempt to start and crash. I have backed out all input manager files per the instructions that have been posted elsewhere. I have re-applied the 10
-
How to handle transaction SWEC
Hi All , I need to understand how and what transaction SWEC does.Please kindly help me. and Also , specifically I need to know what is FIELD RESTRICTION for. Please reply.
-
Framing an item using the Frame Chaeel - PS CS5
Under Window there is Actions and one of the actions is Frame Channel. When I click Fram Chanel nothing happens but it does expand and some stuff is listed below it. Each time I double click one of the listed items again nothing happens. I was wonder
-
im really sad