DB2 Save the picture and read the animated display picture

Source: Internet
Author: User

Blog background:

Customers require structured picture information, not the management of documents and documents, it is required to store the picture information in the DB2, from a technical point of view, really do not like to store files in the database,

But the customer is God, the wood has the method, therefore has the following test.

Test environment: DB2 V9.7 JDK7 spring3.x tomcat8

Native test results: The dynamic acquisition of the first access to the speed is directly obtained 1/20, if the cache can not be compared.

Time detection uses chrome and Firfox's F12 tools.

Write test code in the process of reference to a lot of articles on the Internet, found that most of the copy to copy, it is estimated that the test has not been able to pass.

Let's take a look at the trouble in the testing process.

1, DB2 Save the database is the BLOB type, Java set to byte[] in order to properly save (Binarystream and Blob failed).

2, read DB2 blob when do not know why use PreparedStatement read, use statement only line.

3, the operation of the IO more unfamiliar.

Table structure:

1. Save the picture

Upload a picture page:

<formAction= "Bs/test/uploadimg.do"Method= "POST"enctype= "Multipart/form-data"Target= "Testframe">ID:<inputtype= "text"name= "id"/><BR/>Name:<inputname= "Name"type= "text"/><BR/>File:<inputtype= "File"name= "img"/><BR/>        <inputtype= "Submit"value= "Submit"/></form><iframesrc=""ID= "Testframe"name= "Testframe"Height= "0"width= "0"frameborder= "0"></iframe>

Background Action Example:

ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream;Importjava.util.List;ImportJava.util.Map;ImportJavax.annotation.Resource;Importjavax.servlet.http.HttpServletRequest;ImportCom.oreilly.servlet.multipart.FilePart;ImportCom.oreilly.servlet.multipart.MultipartParser;ImportCom.oreilly.servlet.multipart.ParamPart;ImportCom.oreilly.servlet.multipart.Part; @Urls ("Uploadimg.do") @Ajax Public voidSaveFile (HttpServletRequest request) {intFileSize = 10; Try{Multipartparser MP=NewMultipartparser (Request, FileSize * 1024 * 1024 );        Part part; intFileCount = 0; byte[] bt =NULL; String name=NULL; String FileName=NULL; String ID= "999"; //traverse all forms in a request             while((Part=mp.readnextpart ())! =NULL){                 if(Part.isfile ()) {//is a fileFilepart fp =(Filepart) part; FileName=Fp.getfilename (); if(Filename.endswith ("png") | | | filename.endswith ("GIF") | | filename.endswith ("jpg") | | filename.endswith ("JPEG")) {                         //The purpose of the output stream is to circulate the input into a byte arrayBytearrayoutputstream out =NewBytearrayoutputstream (); InputStream in=Fp.getinputstream (); intSize = 0; byte[] buffer =New byte[1024];  while(Size=in.read (buffer))!=-1) {out.write (buffer,0, size); } BT=Out.tobytearray (); FileCount++; }Else {                        Throw NewException ("File is not a picture!")); }                 }Else{Parampart pp=(Parampart) part; String InputName=Pp.getname (); if("Name". Equals (InputName)) {Name=Pp.getstringvalue (); }Else if("id". Equals (InputName)) {ID=Pp.getstringvalue (); }                 }            }            if(filecount==0){                Throw NewException ("Please select picture and upload again!")); }             This. Testdao.savefile (FileName, BT, Name,integer.parseint (ID)); } Catch(Exception e) {e.printstacktrace (); }}

Dao Method:

 Public voidSaveFile (FinalString FileName,Final byte[] BT,FinalString name,Final intIdthrowssqlexception{String SQL= "INSERT INTO SDE. T_test_img (Id,file_name,img_file,name) VALUES (?,?,?,?) ";  This. Getjdbctemplate (). Update (SQL,NewPreparedStatementSetter () { Public voidSetvalues (PreparedStatement PS)throwsSQLException {ps.setint (1, id); Ps.setstring (2, FileName); //the following 2 kinds of errors, the online a lot of examples are so written, very surprised ... ..//Ps.setbinarystream (3, FIS, fileSize); //Ps.setblob (3, FIS);Ps.setbytes (3, BT); Ps.setstring (4, name);    }        }); }

2. Read the picture

Front desk:

<inputtype= "button"onclick= "SetUrl ()"value= "Load Picture"/>    <imgsrc=""alt= "Dynamic Generation"ID= "Dimg"/><imgsrc=""alt= "Get Directly"ID= "SIMG"/>

Js:

function SetUrl () {// dynamically generate the same picture document.getElementById ("dimg"). src= "generationimg?id=3"; // direct access to picture document.getElementById ("sImg"). src= "Mobileimage/17074_20130927160025.jpg";}

To process a servlet that generates a picture:

/*** Read BLOB-type images from the database and display them to the foreground*/     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {String ID= Request.getparameter ("id"); Response.setcontenttype ("Image/jpeg"); Testdao Testdao= (Testdao) webapplicationcontextutils.getwebapplicationcontext (Request.getsession (). GetServletContext ()). Getbean (Testdao.class); InputStream ins=NULL; Try{ins=testdao.loadfile (ID); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                //build a picture from an input streamBufferedImage image =NULL; Image=imageio.read (INS); Servletoutputstream out=Response.getoutputstream (); JPEGImageEncoder Encoder=Jpegcodec.createjpegencoder (out);                Encoder.encode (image);        Ins.close ();        Out.flush ();    Out.close (); }

Dao Method:

/*** Read DB2 blob field and convert to stream *@paramID *@return     * @throwsSQLException*/     PublicInputStream loadFile (String ID)throwssqlexception{String SQL= "Select Img_file from SDE. T_test_img where id= "+ID; InputStream ins=NULL; Connection Con= This. Getjdbctemplate (). Getdatasource (). getconnection (); Statement PS=con.createstatement (); ResultSet RS=ps.executequery (SQL);  while(Rs.next ()) {blob blob= Rs.getblob ("Img_file"); INS=Blob.getbinarystream (); }        returnins; //the following writing will be problematic, and the above statement changed to Preparestatement after the value is not obtained, ResultSet is null        /*InputStream ins = This.getjdbctemplate (). Execute (SQL, new PreparedStatementCallback () {public O                Bject doinpreparedstatement (PreparedStatement PS) throws SQLException, DataAccessException {                ResultSet rs = Ps.getresultset ();                Blob blob = Rs.getblob (1);                InputStream ins = Blob.getbinarystream ();            return ins;        }        }); return ins;*/  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.