JDBC stores and reads binary data, and jdbc stores binary data.
The following JSP files are uploaded using the common-fileupload component and stored in the database as binary files.
<% If ("POST ". equalsIgnoreCase (request. getMethod) {// if it is a POST form DiskFileUpload diskFileUpload = newDiskFileUpload (); diskFileUpload. setHeaderEncoding ("UTF-8"); // sets the encoding // parses the uploaded data List <FileItem> list = diskFileUpload. parseRequest (request); for (FileItem fileItem: list) {if (! FileItem. isFormField () {// if it is a file domain // file path, replace the special character String filename = fileItem. getName (). replace ("\", "/"); // obtain the filename = filename. substring (filename. lastIndexOf ("/") + 1); // obtain the file type String filetype = fileItem. getContentType (); // get the file size Int filesize = fileItem. getSize (); Connection conn = null; PrepareStatement preStmt = null; try {conn = DbManager. getConnection (); preStmt = conn. prepareStatement ("inser T into table_name (filename, filetype, size, content, date) values (?,?,?,?,?) "); PreStmt. setString (1, filename); preStmt. setString (2, filetype); preStmt. setInt (3, filesize); preStmt. setBinaryStream (4, fileItem. getInputStream (), filesize); preStmt. setTimestamp (5, newTimestamp (System. currentTimeMills (); preStmt.exe cuteUpdate ();} finally {if (preStmt! = Null) preStmt. close (); if (conn! = Null) conn. close () ;}}}%>
Read Binary files
<% Out. clear (); // clear all output int id = Integer. parseInt (request. getParameter ("id"); // obtain the attachment ID Connection conn = null; PrepareStatementpreStmt = null; ResultSet rs = null; try {conn = DbManager. getConnection (); preStmt = conn. prepareStatement ("select from table_name where id =? "); PreStmt. setInt (1, id); rs initialize prestmt.exe cuteQuery (); if (rs. next () {response. reset (); // reset response. setContentType (rs. getString ("fileType"); // sets the output file type response. setContentLength (ra. getInt ("filesize"); // set the length of the output file. InputStream ins = null; OutputStream ous = null; try {ins = rs. getBinaryStream ("content"); ous = response. getOutputStream (); byte [] B = new byte [1024]; int len = 0; while (len = I Ns. read (B ))! =-1) {ous. write (B, 0, len) ;}} finally {if (ous! = Null) ous. close (); if (ins! = Null) ins. close () ;}} else {out. println ("No Attachment Found:" + id) ;}} finally {if (rs! = Null) rs. close (); if (preStmt! = Null) preStmt. close (); if (conn! = Null) conn. close () ;}%>