Storing PDF as a BLOB on Oracle 9i
Hello,
I need to store a PDF document in ORACLE. I obvioulsy need to store it as a BLOB. I have created a BLOB filled in the table but I have no idea what to do next. Are there any good tutorials on this ? Can someone provide me a very simple code that inserts BLOB and than reads it?
Thanks
Dear All,
try this code it will store image or any file or pdf in to oracle database but,
the only thing you do is to put the table column type as 'LONG RAW'
It stores all the above as BLOBs.
try
// create connection
PreparedStatement pstmt = null;
File f = new File(file_path);
FileInputStream fis = new FileInputStream(f);
// System.out.println("IMG : "+file_name+" Len : "+f.length());
String insert = "insert into table_name values(?)";
pstmt = con.prepareStatement(insert);
pstmt.setBinaryStream(1,fis,(int)f.length());
i = pstmt.executeUpdate();
fis.close();
f = null;
catch(Exception e)
e.printStackTrace();
finally
try{
if(pstmt!=null)
pstmt.close();
if(con!=null)
con.close();
catch(Exception e){}
}
Similar Messages
-
I have being storing PDF files using Blob, but it is getting very time consuming to access these files again.
Is there a better way of doing it? Is there a right way of doing it? I do not need to search inside the PDF, but I do need to access them either inside the Database or outside.
Thank You for nay helpI have a need to store PDF files that are documents that will complement process that my systems creates. And I need that those PDF files be accessible from inside my system, I do not need to search insede them because they will be stored by subject inside another subject, therefore whoever need the files will know were to find it, but to store and to access it is taking longer and longer as more files are added to the first thead.
-
Storing PDF and Word document in oracle database
any idea, how to store PDF and word document using oracle database.
thanksThe common approach is store as BLOB in database, use DBMS_LOB package to handle the loading and reading, sample script source asktom
Also check this thread in Asktom
SQL> create table demo
2 ( id INT PRIMARY KEY,
3 theBlob blob,
4 dummy_col VARCHAR2(1)
5 )
6 /
Table created.
SQL> -- --------------------------------------------------------------
SQL> -- Load a PDF file into a BLOB field and compress the BLOB.
SQL> -- --------------------------------------------------------------
SQL> declare
2 l_blob blob;
3 l_bfile bfile;
4
5 begin
6 insert into demo (id, theBLOB) values ( 1, empty_blob() )
7 returning theBlob into l_blob;
8
9 l_bfile := bfilename( 'BLOB_DIR', 'Test.PDF' );
10 dbms_lob.fileopen( l_bfile );
11
12 dbms_lob.loadfromfile( l_blob,
13 l_bfile,
14 dbms_lob.getlength( l_bfile ) );
15
16 UPDATE demo
17 SET theBlob = utl_compress.lz_compress(l_blob, 6)
18 WHERE id = 1;
19 -- If you don't want compress the LOB just update directly
20 dbms_lob.fileclose( l_bfile );
21 COMMIT;
22 end;
23 /
PL/SQL procedure successfully completed -
Good Morning Everyone,
1) Create a directory(path)
C:\test\test.pdf
2) create a table to hold the BLOB:
create table test(
ID NUMBER,
DOCS BLOB
3) import the file into a BLOB datatype and insert it into the table:
DECLARE
l_bfile BFILE;
l_blob BLOB;
BEGIN
INSERT INTO tab1 (col1)
VALUES (empty_blob())
RETURN col1 INTO l_blob;
l_bfile := BFILENAME('PDF', 'test.pdf');
DBMS_LOB.fileopen(l_bfile, Dbms_Lob.File_Readonly);
DBMS_LOB.loadfromfile(l_blob, l_bfile, DBMS_LOB.getlength(l_bfile));
DBMS_LOB.fileclose(l_bfile);
COMMIT;
END;
I am wondering about the step 3.
Any help,
Thanks,
NYOracle support has a document on this topic that may be of use:
How to Load File Content to a BLOB Field and Unload BLOB Content to a File on the OS #471715.1
Also on the Oracle Directory object the path should not include the actual file name. From your post it is not easy to tell how you created it.
HTH -- Mark D Powell -- -
Storing pdf documents by pages in oracle 9i usinf jsp
Hi ,,,
When pdf doc is gets uploaded it needs to be saved to the db by pages
(Ex. if a doc. has 2 pages 2 records need to be saved to db).
Client should be able to download several documents at once or several pages of the certain document
how to split a pdf document in to pages by using jsp.please don't cross post
http://forum.java.sun.com/thread.jspa?messageID=3874873
Use iText. -
Storing pdf document as pages in oracle 9i using java
hi
When pdf doc is gets uploaded it needs to be saved to the db by pages
(Ex. if a doc. has 2 pages 2 records need to be saved to db).
Client should be able to download several documents at once or several pages of the certain document.And your question is?
http://www.lowagie.com/iText/
http://java.sun.com/docs/books/tutorial/jdbc/index.html -
Display BLOB File (pdf format) from database inside Oracle Form (6i)
hi all.
Apologies for a primitive question owing to the fact that i m new to development. I have a requirement to display a pdf document with in an oracle form. i want to know is there any such control for that? or any hint how to go about it?
thanks in advanceHere I have found my jsp script...
How I get the PDF?
I call my script from pl/sql with
web.show_document('http://my_server/getblob.jsp?id=' || id_from_my_blob_table || '&baza=myhost:1521:sid','_blank');
<%@ page contentType="text/html;charset=windows-1250"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*" %>
<%@ page import="oracle.jdbc.driver.OracleDriver" %>
<%@ page import="oracle.jdbc.driver.OracleResultSet" %>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs= null;
oracle.sql.CLOB clob = null;
oracle.sql.BLOB blob = null;
String datoteka = "";
String host = "http://" + request.getHeader("host") + "/";
%>
<!--Peter Valencic 2003 -->
<html>
<head>
<title></title>
</head>
<%
String tip ="";
String id ="";
String baza ="";
String shema ="";
try
id = request.getParameter("id");
baza = request.getParameter("baza");
shema = request.getParameter("shema");
if (request.getParameter("id")== null)
throw new Exception("id= null");
else if(request.getParameter("id").equals(""))
throw new Exception("id= null");
if (request.getParameter("baza")== null)
throw new Exception("baza= null");
else if(request.getParameter("baza").equals(""))
throw new Exception("baza= null");
if (request.getParameter("shema") == null)
shema ="";
else if (request.getParameter("shema").equalsIgnoreCase(""))
shema="";
else
shema =shema + ".";
catch(Exception e)
out.println("Priąlo je do napake: " + e.toString());
return;
try
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@"+baza,"your_user","your_password");
stmt =con.createStatement();
rs = stmt.executeQuery ("Select * from "+shema+"DOK_VSEBINA_DOKUMENTA_BLOB where ID="+id);
boolean podatkib = rs.next();
if (!podatkib)
out.print("<li>Ni podatkov za ID="+id);
return;
blob = ((oracle.jdbc.OracleResultSet)rs).getBLOB("VSEBINA");
datoteka = rs.getString("NAZIV_DATOTEKE").toUpperCase();
File blobFile = new File(application.getRealPath("/uploads/blob")+"/"+datoteka);
blobFile.createNewFile();
InputStream podatki = blob.getBinaryStream();
FileOutputStream strBlob= new FileOutputStream(blobFile);
int size = blob.getBufferSize();
byte[] buffer = new byte[size];
int length = -1;
while ((length = podatki.read(buffer)) != -1)
strBlob.write(buffer,0,length);
podatki.close();
strBlob.close();
con.close();
out.print("<li>"+host+"in2/uploads/blob/"+datoteka);
response.sendRedirect(host+"in2/uploads/blob/"+datoteka);
//odpremo z jsp-stranjo datoteko..
//response.sendRedirect("");
catch(Exception blobException)
out.print("<li>(BLOB)Napaka pri prebiranju podatkov:</li>"+blobException.toString());
return;
out.println("konec..");
%>
<body>
<form method="post">
Vnesi ID
<input type=text name="id">
<li> <input type=submit name="potrdi" >
</form>
</body>
</html>If you look my "old" script..
first it get 2 parameters baza= database (ip:port:sid), id= id from my table (PK)
at the end of my script I have:
response.sendRedirect(host+"in2/uploads/blob/"+datoteka);
this redirect will redirect you to your file stored on server side..
Because IE knows what file it must open it will open it with PDF reader...
hope this help you..
Edited by: peterv6i.blogspot.com on May 14, 2012 11:14 AM -
To upload a PDF file in BLOB column using Oracle Forms 9i
Can anyone tell me how to upload a PDF file from client system using File dialog window and store its content in BLOB column in a table. The file to be uploaded will be in client side.
Take a look at the following :
Re: Storing a PDF in a BLOB
Re: Retrive Image from DB into Image_item
although the threads above are reffered to images and word doc... the procedure/steps are the same....
Greetings...
Sim -
How to show an image stored by using SQLLDR as BLOB in ORACLE 10g
Hi!
i used SQLLDR to upload images from localhost to my oracle db,
i saves theme as BLOB`s.
my problem is:
i can not view them correctly, showing it using the code below, i get:
gtìSNEvR=Cm¯ö¾ÆTÿmÖØÏs_û«¬ú ÿSê¯HwýÓ [[ü/ñÝßSº¢
does any know what to do?? can help me??
thank you!
A.H.S.
<?php
echo "<p>Attempting database connection...</p></p>";
$db_conn = ocilogon("username", "password", "ORACLE_SID");
if (!$db_conn)
echo "...FAILED. Check the username, passwd, dbstring given in this script are valid or not.</p>";
if (OCIError($db_conn))
$erra=OCIError($db_conn);
dodberror("SQL Error: $erra $erra[message]");
exit;
else
echo "<p>Connected...</p></p>";
$table_name="images";
$stmt = ociparse($db_conn, "select * from $table_name" );
if (!$stmt)
echo '<p>parsing error</p></p>';
if (!ociexecute($stmt,OCI_DEFAULT))
echo "<font color='red'><p>query execute error!</p></font>";
echo "<table border=1 cellspacing='0' width='50%'>\n";
$ncols = OCINumCols($stmt);
echo "<tr>\n";
for ($i = 1; $i <= $ncols; $i++) {
$column_name = OCIColumnName($stmt,$i);
echo "<td><b>$column_name</b></td>\n";
while (OCIFetch($stmt))
echo "<tr>\n";
for ($i = 1; $i <= $ncols; $i++)
$column_name = OCIColumnName($stmt,$i);
$column_value = OCIResult($stmt,$i);
if($column_name=="DATA")
//Header("content-type: image/jpg");
$image = "$column_value->load()";
echo $column_value; // gives OBJECT!
echo "<td><img src='$image' width='48' height='48' align='middle' border='0' alt='not found'> </td>\n";
//echo "<td><img src='$column_value.jpg' width='48' height='48' a-lign='middle' border='0' alt='not found'> </td>\n"; //works 100%
//$c1 = '<IMG height=128 width=600 SRC="http://host/' . $row[2] . '">';
//if ($row[image]) {
//header("Content-Type: $row[image_type]");
//print "$row[image]";
else
echo "<td><b>$column_value</b></td>\n";
echo "</tr>\n";
echo "</tr>\n";
echo "</table>\n";
OCIFreeStatement($stmt);
OCILogoff($db_conn);
?>Do you need to uncomment one of the header() functions? Make sure
it is called before any text or whitespace is sent.
Look at the example in PHP 5 Code to Upload and Retrieve an Image (aka BLOB) with Oracle
-- cj -
Embedding a *.pdf or *.doc into a Oracle Report
Report Guru's,
I am having a scenario wherein a client wants to import a file which could be anything from an image/text/pdf/doc/excel into an Oracle Report output. The file would be stored in the database table column(BLOB or LONG RAW type). As per the existing functionality available in Oracle Report, I can select this particular column in my report and in the layout design a field with this column as its source. Now the problem is that if I check the properties of this field in the column, then the file format is restricted to text/image/ole/cgm/oracle drawing format/sound/video/ole2/image url and it doesn't seem to take care of pdf/excel or other file types.
Is there any workaround which I can use to embed pdf's or other documents?
Thanks in advance.
Regards.I asked this, too, not too long ago, but I have received no response of any kind.
Seems like maybe the answer is no.
]{evin -
Hi Guys,
I know this is a borderline ApEx problem but I have a page whose sole job is to open a pdf from a blob stored in the database.
This code works for most client machines:
DECLARE
l_blob blob;
BEGIN
SELECT letter INTO l_blob
FROM letters
WHERE lett_id = :P44_LETT_ID;
-- owa_util.mime_header('application/pdf',false);
-- tried pdf and octet they work the same?????
owa_util.mime_header('application/octet',false);
htp.p('Content-Length: ' || dbms_lob.getlength(l_blob));
owa_util.http_header_close;
wpg_docload.download_file(l_blob);
END;
On some machines I get 'Windows cannot open this file ...File: f[7] ...To open this file..........
On most machines this works fine.
I haven't got it to fail with Firefox yet, just IE but only a few machines running IE. Client getting annoyed and I starting to stress.
Many thanks
GaryHave you already tried adding
htp.p('Content-Disposition: attachment; filename...as described here?
http://download.oracle.com/docs/cd/B32472_01/doc/appdev.300/b32469/up_dn_files.htm#CIHDDJGF
Maybe it solves the problem, in case IE is a little bit picky. But I really don't know.
Patrick
My APEX Blog: http://inside-apex.blogspot.com
The ApexLib Framework: http://apexlib.sourceforge.net
The APEX Builder Plugin: http://sourceforge.net/projects/apexplugin/ -
To visualize pdf, doc in blobs
Its possible, to allow the visualization of the content of archives pdf, DOC that had been stored in the type blob (in the Edit Value window of the blob column)?
Rendering PDFs and Microsoft Word Docs is a pretty big ask.
Have you looked into CTX_DOC ?
You may be able to do a view that will convert the document blob into text in a CLOB
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:25695084847068
May give you an idea -
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 PDF file into DB & restoring back to Filesystem
Hi Everybody,
I need to store PDF files into Database (Oracle 8.1.6 on Windows NT). This I could do using DBMS_LOB Package. Now, my problem is bringing back the PDF files to OS filesystem.
I feel my problem will be solved if I have UTL_LOB Package Object in my Database. Where can I get the script or utility that installs the said Object in my Database. Kindly send me the script/utility if anybody has.
Thanks & Regards,
Durai.look,
http://stackoverflow.com/questions/2347842/storing-pdf-files-as-binary-objects-in-sql-server-yes-or-no
Please use Marked as Answer if my post solved your problem and use
Vote As Helpful if a post was useful. -
Serialization Object and storasge in blob field Oracle 8.1.6
Hi,
this is problem with serializing and deserializing when i am storing object serialized in a Blob field Oracle:
MyObject myObject = new MyObject();
ByteArrayOutputStream bayos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream (bayos);
oos.writeObject(myObject);
oos.flush();
byte[] buffer = bayos.toByteArray();
int size = buffer.length;
oos.close();
ByteArrayInputStream bayis = new ByteArrayInputStream(buffer,0,size);
// if the number bytes of serialized myObject > 4kbytes then the insert in Blob field fails down.
// if the number bytes of serialized myObject < 4kbytes then the insert in Blob field successes.
// So I only can put in Blob field serialized object with size minus 4k.
// The code for insert:
PreparedStatement pstmt = connection.prepareStatement(sqlInsert);
pstmt.setBinaryStream(1,bayis,size);
int retCode = pstmt.executeUpdate();
// The code for read from table Oracle
rset = stmt.rxecuteQuery(sqlSelect);
rset.next();
oracle.sql.BLOB fldBlob = (BLOB)rset.getObject(1);
InputStream ins = fldBlob.getBinaryStream();
byte[] buf = new byte[size]
ByteArrayInputStream bayis = new ByteArrayInputStream(buf,0,size);
ObjectInputStream ois = new ObjectInputStream(bayis);
MyObject myObject = (MyObject)ois.readObject();
Someone knows the reason of the limit of 4Kbyte ?
Thanks....Insert LOBs into Oracle is a 3 step process. You must insert a place holder, and the do a select for update to put the contents into the row. Lets say you have a table called MY_LOB:
create table MY_LOB (
MYID NUMERIC(10) NOT NULL,
MYLOB BLOB DEFAULT EMPTY_BLOB()
);The 'empty_blob' keyword tells Oracle to put a dummy value in the blob column when a row is initially created. To insert (assuming you have a db connection already):
conn.setAutoCommit(false);
PreparedStatement pstmt = null;
ResultSet rs = null;
oracle.sql.BLOB myLob = null;
try
//Insert the initial row.
pstmt = conn.prepareStatement("INSERT INTO MY_LOB (MYID) VALUES (?)");
//Set the PK value
pstmt.setInt(1,100);
pstmt.executeUpdate();
pstmt.close();
//Lock the row for insertion. This is needed for large inserts.
pstmt = conn.prepareStatement("SELECT MYLOB from MY_LOB where MYID = ? FOR UPDATE");
pstmt.setInt(1,100);
rs = pstmt.executeQuery();
if (rs.next())
myLob = (oracle.sql.BLOB)rs.getBlob(1);
rs.close();
pstmt.close();
//Finally...update the row with the blob data....
myLob.putBytes(1, buffer);
pstmt = conn.prepareStatement("UPDATE MY_LOB SET MYLOB = ? WHERE MYID = ?");
pstmt.setBlob(1, myLob);
pstmt.setInt(2,100);
pstmt.executeUpdate();
pstmt.close();
conn.commit();
catch(SQLException sqlE)
conn.rollback();
finally
//make sure and close all statements....
}Hope this helps, I didn't compile it so it may have some bugs. It should lead in the right direction at least.
Maybe you are looking for
-
VS2012 removing Package folder for SharePoint 2013
Hi, Has anybody faced a problem with Visual studio 2012 where it removes the package folder automatically when you open the project and working in a team. After that it throws error in publishing and deploying and one has to readd this folder from ba
-
Publishing to non .mac account problem
Hi HELP! I think I have bitten off more than I can chew.... Having fallen in love with iWeb I took the plunge and published the website I created to my Partners site (as the iWeb one I wrote was 100% better than his) I used 'Easy Iweb Publisher' to u
-
Missing Acount Assignment Error
Hi, We use activity act assigned networks to raise PR/Reservation when activity is released.I have attached a material component and a service activity element to an internal activity and am trying to release the activity to get the PR/Reservation bu
-
hi, How to find out the blocking sessions in RAC
-
I recently bought Final Cut Studio 2 and my MacBook Pro does not read the Dual Layered discs. Once I insert them, it makes a lot of noise for 30 seconds then spits it back out. Is there any way to fix this so that I can install the programs? Thanks f