Insert picturetext (blobclob) to Oracle database

xiaoxiao2021-03-06  41

Reference: http://www.weste.net/2004/11-3/12250047377.HTML We often encounter problems when writing OA is the storage problem of employee picture files, and there are two ways to solve this problem.

1. Read the image on the web server in the JSP / HTML page, which is to put the picture (upload) to the web server, then read with the HTML statement:

2. That is to upload it into the database. About the Oracle database, it supports BLOB, and Clob, respectively corresponds to pictures and text (long strings)

Due to performance reasons, we still have to use the second method, and save it to the database is easier to manage, is it?

First, we have to solve the upload problem, here the FileUpload Class inside the Apache Commons assembly in the universal use.

Specific steps such as:

DiskfileUpload DFU = New DiskfileUpload ();

Dfu.setsizemax (100000000);

Dfu.setsizetHold (100000);

Dfu.setRepositoryPath ("f: // public");

Try {

List fileItems = dfu.parsequest (required);

Iterator i = fileItems.Item ();

While (I.hasNext ()) {

FileItem Fi = (fileItem) i.next ();

IF (! fi.isformfield ()) {

Name = FI.GETNAME ();

SIZE = fi.getsize ();

IF ((Name == Null || Name.equals (")) && size == 0)

CONTINUE;

}

Name = FI.GETNAME ();

SIZE = fi.getsize ();

INPUTSTREAM IS = fi.getinputStream ();

}

The above code is the code that the web server accepts uploaded. The reference file is already given in the upload text file I wrote. Today, I finally want to understand:

DFU.SetRepositoryPath ("f: // public");

It turned out that the escape character is also said that / n / t, etc., and it is necessary to print the backslash. In fact, this problem is originally known, but because the experience has not been written by the image, I feel very deep, it is very terrible. , Haha, my heart is a bit fear. It seems that the foundation is very important, then there is a little bit of small details, and then there is a Java IO problem. I suddenly found it when I read the IO when I read it Java. But I didn't pay attention!

The file has been uploaded by the above code. Then, we want to implement the JDBC data source link, the purpose is to insert the data into Oracle.

Context ctx = new initialContext ();

DataSource DS = (Datasource) CTX.lookup ("JDBC / AsDbCoreds");

CONN = ds.getConnection ();

Conn.setautocommit (false);

About Import Java.sql. * Javax.sql. * Java.naming. * No longer detailed

Then according to a very useful article, insert the blob type must first 1. Insert an empty

String insert = "Insert INTO UPLOADPICTURE"

"" ?, espty_blob () ";

2. Then find the cursor inside the blob of Oracle:

String Findcursor = "SELECT Content" "from UploadPicture"

"Where name =? for update";

Pay attention to this for update (note !!! Must add for update, this will lock the line until the line is modified, the guarantee does not generate concurrency. It is still difficult to understand, let go of it first)

3. Then modify

String Update = "Update UploadPicture"

"SET Content =?"

"Where name =?";

The question mark here is written for the prepaaredStatement parameter!

Write this program to use Oracle.Sql.blob Class, this class is used to operate the BLOB data type

When we get the ResultSet object

BLOB = (blob) rs.getblob (1);

I don't know how to deal with it. What is blob? String, int, long? I don't understand now! It is estimated that people on 9CBS don't understand, otherwise I will send a post for a long time, no one answer, maybe it is very bad, maybe It's too simple, everyone dismisses, it seems that I have to continue to catch up!

Not complaining, return to the program (always feel that his divergent thinking is very strong, it seems that the writing procedure can not be like this, thanks to java is a pure object-oriented language, if the process is troubles)

How do we handle this blob? Answer is, no matter what it is, write bufferedoutputstream out1 = new bufferedoutputstream (blob.getbinaryoutputstream ());

Here is the stream of buffering such as BLOB (Note getBinaryoutputStream () has not been used, must have a better way to replace!), Say the flow, I am still a little dizzy, there are a lot, I don't know if I use it. Which is better!

The foundation is very important, this is my oral zero, here is a stream reading and writing, some streams read bytes from files or other locations (eg, fileInputstream), written, write flow The section is combined with useful data (such as DataInputStream). When we read the numbers, you need to first recommend a fileInpustream, then, then pass the objects of the class to DataInputStream.

FileInputStream Fin = New FileInputStream ("Emp.dat");

DataInputStream DIN = New DataInputStream (FIN); // Pass FIN to DIN

Double s = din.readdouble ();

By default, the stream is not buffered, if you use the buffer is

DataInputStream DIN = New DataInputStream

New BufferedInputStream (New FileInputStream ("Emp.dat"))))))

With this understanding, it is also used.

BufferedoutputStream out1 = new bufferedoutputstream (blob.getbinaryoutputstream ());

It is to build a buffering object to blob. Note that OUT1 here is not OUT, otherwise the TEMP data cannot be printed when running!

Already ready to write, how can I read it?

BufferedInputStream in = New BufferedInputStream (IS);

InputStream is = fi.getinputStream ();

Read the picture as the input stream. Save as an IS object, then use it here, ready to read and write, we start working:

INT C;

While ((c = in.read ())! = - 1) {OUT1.WRITE (C);} in.close ();

Out1.close ();

By buffering one read data, then a write data.-1 is the end of the file,

Finally, when you read and write, we have to close the read and write object!

Program analysis is the case, and will also study this issue later, and finally pay attention,

<% @ Page ContentType = "Image / JPEG; Charset = GBK"%>

Not

<% @ page contenttype = "text / html; charset = GBK"%>

Otherwise, it is displayed in text - garbled.

Here, I have studied the procedures in Oralce in Oralce. About the display, I have to trouble, I have realized it with the information, and I will study it tomorrow.

// Plug into the upload picture to the database

<% @ page contenttype = "text / html; charset = GBK"%>

<% @ Page Import = "java.util. *"%>

<% @ Page Import = "java.io. *"%>

<% @ Page Import = "org.apache.commons. *"%>

<% @ page import = "org.apache.commons.fileUpload. *"%>

<% @ Page Import = "java.sql. *"%>

<% @ Page Import = "javax.sql. *"%>

<% @ Page Import = "javax.naming. *"%>

<% @ Page Import = "Oracle.sql. *"%>

getPicture.jsp </ title></p> <p></ hEAD></p> <p><body></p> <p><%</p> <p>Request.SetCharacterencoding ("GBK");</p> <p>String name = NULL;</p> <p>Long size = 0;</p> <p>Connection conn = NULL;</p> <p>String insert = "Insert INTO UPLOADPICTURE" </p> <p>"" ?, espty_blob () ";</p> <p>String FindCursor = "SELECT Content" </p> <p>"from UploadPicture" </p> <p>"Where name =? for update";</p> <p>String Update = "Update UploadPicture" </p> <p>"SET Content =?" </p> <p>"Where name =?";</p> <p>BLOB BLOB = NULL;</p> <p>InputStream IS = NULL;</p> <p>DiskfileUpload DFU = New DiskfileUpload ();</p> <p>Dfu.setsizemax (100000000);</p> <p>Dfu.setsizetHold (100000);</p> <p>Dfu.setRepositoryPath ("f: // public");</p> <p>Try {</p> <p>List fileItems = dfu.parsequest (required);</p> <p>Iterator i = fileItems.Item ();</p> <p>While (I.hasNext ()) {</p> <p>FileItem Fi = (fileItem) i.next ();</p> <p>IF (! fi.isformfield ()) {</p> <p>Name = FI.GETNAME ();</p> <p>SIZE = fi.getsize ();</p> <p>IF ((Name == Null || Name.equals (")) && size == 0)</p> <p>CONTINUE;</p> <p>}</p> <p>Name = FI.GETNAME ();</p> <p>SIZE = fi.getsize ();</p> <p>IS = fi.getinputstream ();</p> <p>}</p> <p>Context ctx = new initialContext ();</p> <p>DataSource DS = (Datasource) CTX.lookup ("JDBC / AsDbCoreds");</p> <p>CONN = ds.getConnection ();</p> <p>Conn.setautocommit (false);</p> <p>// Step 1</p> <p>PreparedStatement PS = conn.preparestatement (Insert);</p> <p>Ps.setstring (1, name);</p> <p>INT a = ps.executeUpdate ();</p> <p>IF (a> 0)</p> <p>Out.println ("INSERT SUCCESS!" "<br>");</p> <p>// Step 2</p> <p>PS = conn.preparestatement (FindCursor);</p> <p>Ps.setstring (1, name);</p> <p>ResultSet RS = ps.executeQuery ();</p> <p>While (rs.next ())</p> <p>{</p> <p>BLOB = (blob) rs.getblob (1);</p> <p>Out.println ("Find Cursor Success!" "<BR>");</p> <p>Out.println ("Cursor:" BLOB "<BR>");</p> <p>// step 3</p> <p>PS = conn.preparestatement (Update);</p> <p>Ps.setblob (1, blob);</p> <p>Ps.setstring (2, name);</p> <p>ps.executeUpdate ();</p> <p>ps.close ();</p> <p>BufferedoutputStream out1 = new bufferedoutputstream (blob.getbinaryoutputstream ());</p> <p>BufferedInputStream in = New BufferedInputStream (IS);</p> <p>INT C;</p> <p>While ((c = in.read ())! = - 1) {OUT1.WRITE (C);}</p> <p>In.Close ();</p> <p>Out1.close ();</p> <p>Out.println ("Update Success!" "<br>");</p> <p>CONN.COMMIT ();</p> <p>}</p> <p>Catch (SQLException SE)</p> <p>{se.printstacktrace ();</p> <p>FileUploadexception Fue)</p> <p>{Fue.PrintStackTrace ();}</p> <p>%></p> <p></ body></p> <p></ html></p> <p>/ / Display image in the database <% @ page contentty = "image / jpeg; charset = GBK"%></p> <p><% @ Page Import = "java.sql. *"%></p> <p><% @ Page Import = "javax.sql. *"%></p> <p><% @ Page Import = "javax.naming. *"%></p> <p><% @ Page Import = "java.io. *"%></p> <p><% @ Page Import = "com.sun.image.codec.jpeg. *"%></p> <p><% @ Page Import = "javax.imageio. *"%></p> <p><% @ Page Import = "java.util. *"%></p> <p><% @ Page Import = "java.awt.image. *"%></p> <p><html> <head> <meta http-equiv = "content-type" content = "image / jpeg; charset = GBK"> <title> showdbimage.jsp </ title> </ head> <body> <% string showimage = "select *" "from uploadpicture" "where name = 'TXC with snow.JPG'"; Connection conn = null; BufferedInputStream inputImage = null; try {Context ctx = new InitialContext (); DataSource ds = (DataSource) CTX.lookup ("jdbc / askBCOREDS"); conn = ds.getConnection (); statement st = conn.createstatement (); resultset = st.executeQuery; while (rs.next ()) {Oracle.sql .Blob blob = (oracle.sql.blob) rs.getblob ("content"); inputiMage = new bufferedinputStream (blob.getbinarystream ()); / * String name = rs.getstring (1); string content = rs.getstring (2); out.println (name "<br>"); * /} BufferedImage image = null; image = ImageIO.read (inputImage); ServletOutputStream sos = response.getOutputStream (); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (sos Encoder.encode (image); Inputi Mage.close (); conn.com (sqlexception se) {se.printstacktrace (); conn.rollback ();} catch (ooexception ie) {IE.PrintStackTrace ();}%> </ body > </ html></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-52517.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="52517" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.040</b>, SQL: <b>12</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'F7PzQBLQ9RXKl7q_2Fe3fH_2BmNuP9tL7NbuDh4FRIGO0ONICvbOgZeyQRXSuqDxreX17SF4xCAltITGUKmmK_2Bmlww_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>