BLOB data in Java stored in database __ database

Source: Internet
Author: User
Tags create directory uuid

BLOB (Binary large object), binary large objects, is a container in which binary files can be stored.
In a computer, a blob is often the type of field used in a database to store a binary file.
A blob is a large file, a typical blob is a picture or a sound file and, due to their size, must be handled in a special way (for example, uploading, downloading, or storing to a database).
According to Eric Raymond, the main idea for dealing with blobs is to let the file processor (such as the database Manager) ignore what the file is, and instead care about how to handle it.
However, some experts stressed that this method of dealing with large data objects is a double-edged sword, it may cause some problems, such as the storage of binary files too large, the performance of the database will be degraded. Storing large multimedia objects in a database is a typical example of application processing blobs. (above excerpt from Baidu)
Blob field out of library please click here.

1. First, put in a blob, that is, upload the file and save the file to the Database BLOB field
First create a string to store the uploaded file path and name:

String FilePath = "";

Upload the file page and the normal upload file, the same way, use form form to submit servlet processing, note set form form enctype for Multipart/form-data, and then submit to the background servlet, then focus on, Files submitted through form forms, to get this file need to be used

Diskfileitemfactory factory = new Diskfileitemfactory ();
This thing, his role is: Instantiate a hard disk file factory, used to configure the file to build Servletfileupload,
Then create a file upload parser:
Servletfileupload fileupload = new Servletfileupload (factory);
Next to solve the garbled problem:
Fileupload.setheaderencoding ("UTF-8");
The data is then judged by the data that is not submitted by form:

if (!fileupload.ismultipartcontent) {
   return;//If, that means there is a problem, direct return, of course, according to the actual situation of different processing

Then create a temporary path for storing temporarily uploaded files for storing blobs

String path = This.getservletcontext (). Getrealpath ("/web-inf/upload");
File File = new file (path);//is placed under the Web-inf folder because it is more secure
//To determine if the saved directory of the uploaded file exists if
 (!file.exists () &&! File.isdirectory ()) {
     System.out.println (savepath+ "directory does not exist, needs to be created");
     Create directory
     file.mkdir ();

The next step is to get the submitted file data, where we write list<fileitem>, because if you commit more than one file at a time, you need to receive multiple files:

list<fileitem> filist = fileupload.parserequest (Request)//Use the Servletfileupload parser to parse the uploaded file's data, and the result returned is a list <FileItem> collection, each fileitem corresponds to the input for a form table for (int i = 0;i < Filist.size (); i++) {Fileitem item = filist.get (i //loops through the list///In the loop, because it is submitted from the form form, it is possible to get the non-file data submitted in form, which distinguishes if (Item.isformfield ()) {//If the program enters here, That means the file data that is submitted by}else{String fileName = Item.getname ();//get uploaded filename//Here you need to note that different browsers submit different file names, and some will be linked with the path of the file stored together
     Get, so need to process to get filename filename = filename.substring (Filename.lastindexof (file.separator) +1);/This is the filename part of the filename. String time = new SimpleDateFormat ("YYYYMMDDHHMMSS"). Format (new Date ()) + ' _ ' + new Random (). Nextint (1000);//Create a time s
     Tring, prevent the possibility of filename duplicate filename + time; InputStream is = Item.getinputstream ()//create file input stream FileOutputStream fos = new FileOutputStream (Path +file.separator+fil
     ENAME); byte buffer[] = new byte[1024];//creates a buffer int length = 0;//that determines whether the data in the input stream has been read out while (length = (buffer) >0) {//loop reads input stream into buffer fos.write (buffer, 0, length);//use FileOutputStream output stream to write buffer data to specified directory Is.close ()//close the input stream Fos.close ()//close the output stream if (I!= filist.size ()-1) {FilePath = FilePath + fi
     lename+ "*"//Record each uploaded file, with * split, with * Split upload each file is because the filename can not have *}else{FilePath = filePath + filename; }

This is where the file to be deposited into the Blob is uploaded to the temporary path, and filepath is the path to all the files we uploaded and is stored in the database with a * separated
. We choose JDBC Mode:

string[] files = Filepath.split ("*");
  for (String fp:files) {class.forname ("oracle.jdbc.driver.OracleDriver");
  According to the database connection character, the name, the password assigns the conn the value conn = drivermanager.getconnection ("url", "User", "password"); Conn.setautocommit (false);//The program must invoke a commit or Rollback method to initialize the driver package, where I use ORACLE,JDBC is the basis, all the same String uuid = Uuid.randomuu ID (). toString ();//Generate a UUID String sql = "INSERT INTO Test (Id,blobvalue) VALUES (' +uuid+" ', Empty_blob ()) "////Insert an empty BLOB first
    Value Empty_blob PreparedStatement pstmt = conn.preparestatement (sql);
    Pstmt.executeupdate ();
    Pstmt.close ();
    pstmt = Conn.preparestatement ("Select Blobvalue from Test where id= '" + uuid + "' for Update");
    ResultSet RSet = Pstmt.executequery ();
    File F = new file (path + "\" +FP);
    InputStream fin = new FileInputStream (f);
            if ( ()) {try{BLOB Oracleblob = (Oracle.sql.BLOB) rset.getblob (1);
            OutputStream out = Oracleblob.getbinaryoutputstream (); Bufferedoutputstream ouTput = new Bufferedoutputstream (out); 
            Bufferedinputstream input = new Bufferedinputstream (FIN); byte[] buff = new byte[2048]; 
            Buffer int Bytesread used as file writes; 
            while ( -1!= (bytesread = (buff, 0, buff.length))) {output.write (buff, 0, bytesread);
            } fin.close ();
            Out.flush ();
        Output.close ();
            }catch (Exception e) {//get stream Oraclethinblob Oracleweblogicblob = (oraclethinblob) rset.getblob (1);
            OutputStream out = Oracleweblogicblob.getbinaryoutputstream (); 
            Bufferedoutputstream output = new Bufferedoutputstream (out); 
            Bufferedinputstream input = new Bufferedinputstream (FIN); byte[] buff = new byte[2048]; 
            Buffer int Bytesread used as file writes; 
            while ( -1!= (bytesread = (buff, 0, buff.length))) {output.write (buff, 0, bytesread); } FIN.CLose ();
            Out.flush ();
        Output.close ();
    } pstmt.executeupdate ();//modify Pstmt.close ();
    Conn.commit (); submit conn.close ();
 F.delete ()//Finally, don't forget to delete temporary files}

Here basically even completes the file uploaded to the database blob I'm here. File upload and stored in the database separately written, asked to facilitate everyone to understand the upload file and deposit blob field, the article Pure hand dozen, may have the wrong place, but the specific ideas and procedures should be no problem, But the program has a lot to optimize the place, such as database connection pool creation written in the For loop, so that each cycle is created, closed will be very expensive computer resources, this article only provides ideas for reference.
Original: Shadow Childe-Reprint please indicate the original link
———————-Java Technology Learning Exchange Group 467047721
Click on the link to join the group "Java Technology Learning Exchange Group": K=48dlkmy

Related Article

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: 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.