/** * Determine the type of attachment, based on file extension, and add it to the elog entry with * the entry_id. * * @param fname input filename, either an image or a text file * @param fileType "I" for image file, "A" for text file * @param entry_id ID of entry to which to add this file * @param caption Caption or 'title' for the attachment * @throws Exception */ private void addFileToElog( final String fname, String fileType, final int entry_id, final String caption) throws Exception { // Get the file extension final int ndx = fname.lastIndexOf("."); final String extension = fname.substring(ndx + 1); long fileTypeID = getFileTypeId(fileType, extension); // If the image type cannot be found in the RDB, change its file type to // an attachment and look for the // extension as an attachment if (fileTypeID == -1 && fileType.equals("I")) { fileType = "A"; fileTypeID = getFileTypeId(fileType, extension); } // Initiate the sql to add attachments to the elog final String mysql = "call logbook.logbook_pkg.add_entry_attachment" + "(?, ?, ?, ?, ?)"; final Connection connection = rdb.getConnection(); final CallableStatement statement = connection.prepareCall(mysql); try { statement.setInt(1, entry_id); statement.setString(2, fileType); statement.setString(3, caption); statement.setLong(4, fileTypeID); final File inputFile = new File(fname); // Send the image to the sql. if (fileType.equals("I")) { try { final int file_size = (int) inputFile.length(); final FileInputStream input_stream = new FileInputStream(inputFile); statement.setBinaryStream(5, input_stream, file_size); input_stream.close(); } catch (FileNotFoundException e1) { System.out.println("Could not find " + fname); return; } } // Send the text attachment to the sql else { // Create a Blob to store the attachment in. final BLOB blob = BLOB.createTemporary(connection, true, BLOB.DURATION_SESSION); blob.setBytes(1L, getBytesFromFile(inputFile)); statement.setBlob(5, blob); } statement.executeQuery(); } finally { statement.close(); } }
/** 针对oracle Blob字段的插入操作 */ @Test public void testBigBlobWrite() { PreparedDBUtil dbUtil = new PreparedDBUtil(); TransactionManager tm = new TransactionManager(); try { // 启动事务 tm.begin(); // 先插入一条记录,blob字段初始化为empty_lob dbUtil.preparedInsert("insert into test(id,blobname) values(?,?)"); String id = DBUtil.getNextStringPrimaryKey("test"); dbUtil.setString(1, id); dbUtil.setBlob(2, BLOB.empty_lob()); // 先设置空的blob字段 dbUtil.executePrepared(); // 查找刚才的插入的记录,修改blob字段的值为一个文件 dbUtil = new PreparedDBUtil(); dbUtil.preparedSelect("select blobname from test where id = ?"); dbUtil.setString(1, id); dbUtil.executePrepared(); BLOB blob = (BLOB) dbUtil.getBlob(0, "blobname"); if (blob != null) { DBUtil.updateBLOB(blob, new java.io.File("d:/dominspector.rar")); } tm.commit(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); try { tm.rollback(); } catch (RollbackException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } finally { tm = null; dbUtil = null; } }
/** Provide functionality for Oracle specific types, such as ROWID. */ public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException { PyObject obj = Py.None; switch (type) { case Types.BLOB: BLOB blob = ((OracleResultSet) set).getBLOB(col); if (blob == null) { return Py.None; } InputStream stream = new BufferedInputStream(blob.getBinaryStream()); obj = Py.java2py(DataHandler.read(stream)); break; case OracleTypes.ROWID: ROWID rowid = ((OracleResultSet) set).getROWID(col); if (rowid != null) { obj = Py.java2py(rowid.stringValue()); } break; default: obj = super.getPyObject(set, col, type); } return (set.wasNull() ? Py.None : obj); }
public static void main(String[] args) { try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); ; Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@192.168.117.110:1521:WFZF", "qzkj", "qzkj"); conn.setAutoCommit(false); ; BLOB blob = null; PreparedStatement pstmt = conn.prepareStatement("insert into sys_file(uuid,content,name) values(?,empty_blob(),?)"); String uuid = Tool.getStringUUid(); pstmt.setString(1, uuid); pstmt.setString(2, "test.flv"); pstmt.executeUpdate(); pstmt.close(); pstmt = conn.prepareStatement("select content from sys_file where uuid= ? for update"); pstmt.setString(1, uuid); ResultSet rset = pstmt.executeQuery(); ; if (rset.next()) blob = (BLOB) rset.getBlob(1); ; String fileName = "test.flv"; File f = new File( "C://Documents and Settings//Administrator//桌面//FlvPlayer201002//FlvPlayer201002//" + fileName); FileInputStream fin = new FileInputStream(f); ; System.out.println("file size = " + fin.available()); pstmt = conn.prepareStatement("update sys_file set content=? where uuid=?"); ; OutputStream out = blob.getBinaryOutputStream(); ; int count = -1, total = 0; byte[] data = new byte[(int) fin.available()]; fin.read(data); ; out.write(data); ; /* byte[] data = new byte[blob.getBufferSize();]; 另一种实现方法,节省内存 while ((count = fin.read(data);); != -1); { total += count; out.write(data, 0, count);; } */ fin.close(); ; out.close(); ; pstmt.setBlob(1, blob); ; pstmt.setString(2, uuid); pstmt.executeUpdate(); ; pstmt.close(); ; conn.commit(); ; conn.close(); ; } catch (SQLException e) { System.err.println(e.getMessage()); ; e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); ; } }
@SuppressWarnings({"unchecked", "deprecation"}) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response_message = ""; HttpSession session = request.getSession(); FileItem image_file = null; int record_id = 0; int image_id; InputStream instream = null; OutputStream full_outstream = null; OutputStream thumb_outstream = null; OutputStream regular_outstream = null; // Check if there is any input in the record id field if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) { response_message = "<p><font color=ff0000>No ID entered!</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } try { // Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List<FileItem> FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator<FileItem> i = FileItems.iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); if (item.isFormField()) { if (item.getFieldName().equals("recordID")) { record_id = Integer.parseInt(item.getString()); if (!isValidID(record_id)) { response_message = "<p><font color=ff0000>Invalid record id!</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } } // out.println(item.getFieldName() + ": " + // item.getString()); } else { image_file = item; if (image_file.getName().equals("")) { response_message = "<p><font color=ff0000>No file selected!</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } } } // Get the image stream instream = image_file.getInputStream(); BufferedImage full_image = ImageIO.read(instream); BufferedImage thumbnail = shrink(full_image, THUMBNAIL_SHRINK); BufferedImage regular_image = shrink(full_image, REGULAR_SHRINK); // Connect to the database db = new Database(); db.connect(); conn = db.getConnection(); stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery(SQL_IMAGE_ID); rset1.next(); image_id = rset1.getInt(1); // Insert an empty blob into the table first. Note that you have to // use the Oracle specific function empty_blob() to create an empty // blob stmt.execute( "INSERT INTO pacs_images VALUES(" + record_id + "," + image_id + ", empty_blob(), empty_blob(), empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB thumb = ((OracleResultSet) rset).getBLOB("thumbnail"); BLOB regular = ((OracleResultSet) rset).getBLOB("regular_size"); BLOB full = ((OracleResultSet) rset).getBLOB("full_size"); // Write the image to the blob object full_outstream = full.getBinaryOutputStream(); ImageIO.write(full_image, "jpg", full_outstream); thumb_outstream = thumb.getBinaryOutputStream(); ImageIO.write(thumbnail, "jpg", thumb_outstream); regular_outstream = regular.getBinaryOutputStream(); ImageIO.write(regular_image, "jpg", regular_outstream); stmt.executeUpdate("commit"); response_message = "<p>Upload OK!</p>"; session.setAttribute("msg", response_message); response.sendRedirect("uploadImage.jsp"); } catch (Exception ex) { response_message = ex.getMessage(); } finally { if (instream != null) { instream.close(); } if (full_outstream != null) { full_outstream.close(); } if (thumb_outstream != null) { thumb_outstream.close(); } if (regular_outstream != null) { regular_outstream.close(); } db.close(conn, stmt, null, rset); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Variable initializations. HttpSession session = request.getSession(); FileItem image_file = null; int record_id = 0; int image_id; // Check if a record ID has been entered. if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) { // If no ID has been entered, send message to jsp. response_message = "<p><font color=FF0000>No Record ID Detected, Please Enter One.</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("UploadImage.jsp"); } try { // Parse the HTTP request to get the image stream. DiskFileUpload fu = new DiskFileUpload(); // Will get multiple image files if that happens and can be accessed through FileItems. List<FileItem> FileItems = fu.parseRequest(request); // Connect to the database and create a statement. conn = getConnected(drivername, dbstring, username, password); stmt = conn.createStatement(); // Process the uploaded items, assuming only 1 image file uploaded. Iterator<FileItem> i = FileItems.iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); // Test if item is a form field and matches recordID. if (item.isFormField()) { if (item.getFieldName().equals("recordID")) { // Covert record id from string to integer. record_id = Integer.parseInt(item.getString()); String sql = "select count(*) from radiology_record where record_id = " + record_id; int count = 0; try { rset = stmt.executeQuery(sql); while (rset != null && rset.next()) { count = (rset.getInt(1)); } } catch (SQLException e) { response_message = e.getMessage(); } // Check if recordID is in the database. if (count == 0) { // Invalid recordID, send message to jsp. response_message = "<p><font color=FF0000>Record ID Does Not Exist In Database.</font></p>"; session.setAttribute("msg", response_message); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); } } } else { image_file = item; if (image_file.getName().equals("")) { // No file, send message to jsp. response_message = "<p><font color=FF0000>No File Selected For Record ID.</font></p>"; session.setAttribute("msg", response_message); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); } } } // Get the image stream. InputStream instream = image_file.getInputStream(); BufferedImage full_image = ImageIO.read(instream); BufferedImage thumbnail = shrink(full_image, 10); BufferedImage regular_image = shrink(full_image, 5); // First, to generate a unique img_id using an SQL sequence. rset1 = stmt.executeQuery("SELECT image_id_sequence.nextval from dual"); rset1.next(); image_id = rset1.getInt(1); // Insert an empty blob into the table first. Note that you have to // use the Oracle specific function empty_blob() to create an empty blob. stmt.execute( "INSERT INTO pacs_images VALUES(" + record_id + "," + image_id + ", empty_blob(), empty_blob(), empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE"; rset = stmt.executeQuery(cmd); rset.next(); BLOB myblobFull = ((OracleResultSet) rset).getBLOB(5); BLOB myblobThumb = ((OracleResultSet) rset).getBLOB(3); BLOB myblobRegular = ((OracleResultSet) rset).getBLOB(4); // Write the full size image to the blob object. OutputStream fullOutstream = myblobFull.getBinaryOutputStream(); ImageIO.write(full_image, "jpg", fullOutstream); // Write the thumbnail size image to the blob object. OutputStream thumbOutstream = myblobThumb.getBinaryOutputStream(); ImageIO.write(thumbnail, "jpg", thumbOutstream); // Write the regular size image to the blob object. OutputStream regularOutstream = myblobRegular.getBinaryOutputStream(); ImageIO.write(regular_image, "jpg", regularOutstream); // Commit the changes to database. stmt.executeUpdate("commit"); response_message = "<p><font color=00CC00>Upload Successful.</font></p>"; session.setAttribute("msg", response_message); instream.close(); fullOutstream.close(); thumbOutstream.close(); regularOutstream.close(); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); instream.close(); fullOutstream.close(); thumbOutstream.close(); regularOutstream.close(); // Close connection. conn.close(); } catch (Exception ex) { response_message = ex.getMessage(); } }
public static void sendToOracle(BeanAccesSQL DBSQL, LinkedList<Posters> posters, int idFilm) throws Exception { ArrayDescriptor ListString = ArrayDescriptor.createDescriptor("LISTVARCHAR2", DBSQL.getConnection()); ArrayDescriptor ListInt = ArrayDescriptor.createDescriptor("LISTNUMBER", DBSQL.getConnection()); ArrayDescriptor ListBlob = ArrayDescriptor.createDescriptor("LISTBLOB", DBSQL.getConnection()); String requete = "{ call PACKAGE_CB.EncoderPosters(?,?,?,?,?,?)}"; CallableStatement csmt = null, smt2 = null; byte[] imageInByte = null; Statement smt = null; int count = 0, nbCover = 0; InputStream isImage = null; LinkedList<Posters> listCover = new LinkedList<>(); for (Posters p : posters) { if (p.getImage().getSize().equals("cover")) { count++; listCover.add(p); if (count == 4) break; } } String[] id = new String[count]; String[] url = new String[count]; String[] size = new String[count]; int[] height = new int[count]; int[] width = new int[count]; BLOB[] img = new BLOB[count]; int i = 0; for (Posters s : listCover) { id[i] = s.getImage().getId(); height[i] = s.getImage().getHeight(); width[i] = s.getImage().getWidth(); url[i] = s.getImage().getUrl(); size[i] = s.getImage().getSize(); i++; } nbCover = i; for (i = 0; i < nbCover; i++) { try { URL urlImage = new URL(url[i]); BufferedImage image = ImageIO.read(urlImage); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", baos); baos.flush(); imageInByte = baos.toByteArray(); baos.close(); img[i] = BLOB.createTemporary(DBSQL.getConnection(), false, BLOB.DURATION_SESSION); OutputStream outputStream = img[i].setBinaryStream(0L); ByteArrayInputStream inputStream = new ByteArrayInputStream(imageInByte); byte[] buffer = new byte[img[i].getBufferSize()]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); } catch (IOException ex) { Logger.getLogger(Posters.class.getName()).log(Level.SEVERE, null, ex); } } Array arrayId = new ARRAY(ListString, DBSQL.getConnection(), id); Array arraySize = new ARRAY(ListString, DBSQL.getConnection(), size); Array arrayHeight = new ARRAY(ListInt, DBSQL.getConnection(), height); Array arrayWidth = new ARRAY(ListInt, DBSQL.getConnection(), width); Array arrayImg = new ARRAY(ListBlob, DBSQL.getConnection(), img); try { csmt = DBSQL.getConnection().prepareCall(requete); csmt.setArray(1, arrayId); csmt.setArray(2, arraySize); csmt.setArray(3, arrayHeight); csmt.setArray(4, arrayWidth); csmt.setArray(5, arrayImg); csmt.setInt(6, idFilm); csmt.executeUpdate(); csmt.close(); smt = DBSQL.getConnection().createStatement(); smt.executeQuery("commit"); smt.close(); } catch (SQLException ex) { throw new Exception("Poster Exception: " + ex.getMessage()); } }