Elias Sales escreveu:

Galera conseguir gravar no banco de dados, mas o exemplo de como l� o
arquivo n�o deu certo, alguem tem um exemplo de como recuperar arquivos em
campo blob?




----- Original Message ----- From: "CMilfont" <[EMAIL PROTECTED]>
To: "Elias Sales" <[email protected]>
Sent: Monday, March 14, 2005 4:46 PM
Subject: Re[2]: [cejug-discussao] Tratamento de dados em blob





eh do grupo apache, acho que vem no tomcat 5, se nao entra no projeto
jakarta e procura la que vc acha....

Elias,
Escreveu em Monday, March 14, 2005, 3:54:11 PM:

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

ES> Qual api tem esse pacote?


ES> ----- Original Message ----- ES> From: "David Barbosa Feitosa" <[EMAIL PROTECTED]>
ES> To: <[email protected]>
ES> Sent: Monday, March 14, 2005 3:44 PM
ES> Subject: Re: [cejug-discussao] Tratamento de dados em blob





O Netbeans debuga
eh s� colocar os break points no JSP
e acompanhar na Aba de debug.
flws!

ldaniel wrote:



Oi, pessoal.

S� um coment�rio:

A menos que voc� conhe�a uma forma eficiente de debugar o JSP, n�o �


uma


pr�tica muito boa colocar tanto c�digo Java, pois fica muito mais


dif�cil


encontrar problemas. Quanto ao debug do JSP, estou procurando um jeito


ES> (sei


que tem gente que faz), mas n�o conhe�o ainda. Ent�o, se algu�m souber


e


quiser compartilhar, eu ficaria grato.

[]s.

----- Original Message ----- From: "Elias Sales" <[EMAIL PROTECTED]>
To: <[email protected]>; "CMilfont" <[EMAIL PROTECTED]>
Sent: Wednesday, March 02, 2005 18:59
Subject: Re: [cejug-discussao] Tratamento de dados em blob







Valeu cara vou testar...

----- Original Message ----- From: "CMilfont" <[EMAIL PROTECTED]>
To: "Elias Sales" <[email protected]>
Sent: Wednesday, March 02, 2005 10:04 AM
Subject: Re: [cejug-discussao] Tratamento de dados em blob







ve se esses codigos te ajudam...

jsp com um exemplo de insercao:

<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>

<%
if (FileUpload.isMultipartContent(request)) {
              DiskFileUpload fu = new DiskFileUpload();
              fu.setSizeMax(800000);
              try {
                      List items = fu.parseRequest(request);
                      Iterator i = items.iterator();
                      FileItem fi;
                      String cmt=null;

                      while (i.hasNext()) {
                              fi = (FileItem)i.next();
                              if (fi.isFormField()) {
                                      cmt = fi.getString();
                              } else{

int size = (int)


fi.getSize();


byte [] imagem = new


ES> byte[size];


                                      imagem = fi.get();

//upload.read(imagem, 0,


size);






Class.forName("com.mysql.jdbc.Driver");




                                      Connection con =




DriverManager.getConnection("jdbc:mysql://localhost:3306/sistema?user=root


&


ES> p




assword=");




                                      PreparedStatement pstm =




con.prepareStatement("INSERT INTO tb_fotos (nome, foto) VALUES (?,


?)");




                                      pstm.setString(1, cmt);
                                      pstm.setBytes(2, imagem);
                                      pstm.executeUpdate();
                                      con.close();
                              }
                      }
              } catch (FileUploadException e) {
                      out.print("Erro no upload do arquivo");
              } catch (SQLException e) {
                      out.print("Erro na consulta com o banco de




dados");




              } catch (Exception e) {
                      out.print(e.getMessage());
              }
}else {
      out.print("O Formulario nao possui dados bin�rios");
}

%>

<html>
<body bgcolor="#FFFFFF">
<h2>Fonto inserida com sucesso no banco de dados!</h2>
</body>
</html>

/************************************
exemplo de leitura:

<%@ page language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.awt.*" %>

<%!
byte [] image;
%>

<%
try {
      // criando a conexao com o banco de dados

      Class.forName("com.mysql.jdbc.Driver");
      Connection con =




DriverManager.getConnection("jdbc:mysql://localhost:3306/sistema?user=root


&


ES> p




assword=");




//PreparedStatement pstm =


con.prepareStatement("INSERT INTO




tb_fotos (nome, foto) VALUES (?, ?)");




      Statement stm = con.createStatement();

int codigo;
// pegando o codigo da foto a ser exibida
if (request.getParameter("numero") == null){codigo = 1; }
else{codigo =


ES> Integer.parseInt(request.getParameter("numero"));}


ResultSet rs = stm.executeQuery("SELECT * FROM tb_fotos


WHERE


ES> id




=




"+codigo);




      if (rs.next()) {

              Blob blob = rs.getBlob("foto");




//JPEGManager.encodeJPG(response.getOutputStream(),




blob.getBytes(1, (int) blob.length()));




              image = blob.getBytes(1, (int) blob.length());
              int BUFFER = image.length;
              InputStream fs = new ByteArrayInputStream(image);
              JPEGImageDecoder decoder =




JPEGCodec.createJPEGDecoder(fs);




BufferedImage bImage =


decoder.decodeAsBufferedImage();


              JPEGImageEncoder encoder =




JPEGCodec.createJPEGEncoder(out);




              encoder.encode(bImage);
              fs.close();
              fs = null;
              encoder = null;
              bImage = null;

      }
      con.close();
}catch (Exception e){
      // erro
      %>Erro encontrado<%
}
%>


Elias, Escreveu em Tuesday, March 1, 2005, 7:03:19 PM:

ES> alguem tem algum exemplo de gravar e ler campos em
ES> blob usando mysql?
--
Atenciosamente,
CMilfont
[EMAIL PROTECTED]

--
Curtindo: Pitty Festival de Ver�o 2005 - 01














--

Atenciosamente,

Bruno Miranda
Analista de Sistemas
T�xtil Bezerra de Menezes S.A.
Fone: (85) 4012-9139

Title:






 

 

Abstract

Example of using JAVA Streams with BLOBs - Sample Application

 

Product Name, Product Version

JDBC 8.1.X � 9.2.X

Platform

Generic

Date Created

04-SEP-2002

 

Instructions

Execution Environment:
     JDBC Client connecting
to 8.1.X Server
 
Usage:
     Java BLOBStreams
 
Instructions:
 
 
o  The user the program logs in with
must have create table privileges.
 
 
o  Set ORACLE_HOME, CLASSPATH, and on
UNIX, the LD_LIBRARY_PATH.  For
     example:
 
           CLASSPATH
= .:$ORACLE_HOME/lib:$ORACLE_HOME/jdbc/lib/classes12.zip
          
LD_LIBRARY_PATH = $ORACLE_HOME/lib:...
 
  o  The application
requires a suitable JDK 1.1.x or JDK 1.2, Oracle 8.1.x,
    
JDBC/OCI driver 8.1.x or JDBC/Thin driver.
 
  o  Be sure
to set the appropriate variables (infilePath and outfilePath) to
     reflect the location of the files to work with.
 
 
 
PROOFREAD THIS SCRIPT BEFORE USING IT! Due to differences
in the way text 
editors, e-mail packages, and operating systems handle text
formatting (spaces, 
tabs, and carriage returns), this script may not be in an
executable state
when you first receive it. Check over the script to ensure
that errors of
this type are corrected.The script will produce an output
file named [outputfile].
This file can be viewed in a browser or uploaded for support analysis.

 

Description

This article
contains a Java application that demonstrates the use of Java
streams to load a BLOB into the database from an operating
system file.  
 
The application uses binary stream to load the data and to
fetch and write 
the data back to a file. 
The program was tested on both Solaris and Windows 
NT 4.0 with a 20.55 megabyte file.
 
 
Sample Output
-------------
 
Insert empty blob successful
Select executed
Elapse time to Load blob 36 seconds
Select successful
Get Blob successful.
 Program completed

 

References

 
"Oracle8i JDBC Developer's Guide and Reference Release
8.1.5", (A64685-01)
"Oracle8i JDBC Developer's Guide and Reference Release
8.1.6", (A81354-01)
 

 

Script

//Title:       Demo of BLOB with Streams
//Company:     Oracle
Corporation
//Description: Application to demonstrate using streams with
BLOB data.
//*****************************************************************************
//Notice:
//*****************************************************************************
//The sample program article is provided for educational purposes
only. It is
//NOT supported by Oracle Support Services, however, it has
been tested and
//appears towork as documented. 
Be sure to test this code in your environment
//before relying on it.
//*****************************************************************************
 
import java.io.*;
import java.sql.*;
import javax.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
 
public class BLOBStreams {
 
 
  public BLOBStreams() {
  }
 
  public static void
main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    int fileLength = 0;
    InputStream infstrm = null;
    PreparedStatement
pstmt = null;
    File infile = null;
    File outfile = null;
    int key = 1000;
    BLOB myblob = null;
    OutputStream outstrm
= null;
    int len = 0;
    int bufsize = 0;
 
    //These next two
lines are for use on Microsoft Platforms comment these
    //lines out and
uncomment the two following lines for UNIX Platforms.
    //You will need
to modify these lines to provide a valid path and
    //filename for
your environment.
    //String infilePath
= "D:\\valid_path\\binary_file";
    //String outfilePath
= "D:\\valid_path\\outputfile";
    String infilePath
= "/valid_path/infilename.dat";
    String outfilePath
= "/valid_path/outfilename.dat";
 
 
    new BLOBStreams();
    try{
    DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
    //You will need
to modify the connection string to provide you host,
    //port and SID.
    conn = DriverManager.getConnection("jdbc:oracle:oci8:@",
                                        "scott",
"tiger");
    conn.setAutoCommit(false);
    }
    catch(Exception e){
      System.out.println("Connection
failed.");
      e.printStackTrace();
    }
    try{
       stmt = conn.createStatement();
       stmt.executeUpdate("drop
table blobtable");
    }
    catch(SQLException e){
    //We ignor an exception
raised here.
    }
 
    try{
      stmt = conn.createStatement();
      stmt.executeUpdate("create
table blobtable (key_id NUMBER(4), binarydata blob)");
    }
    catch(SQLException e){
      System.out.println("Create
table failed.");
      e.printStackTrace();
    }
 
        try{
       infile = new
File(infilePath);
       fileLength =
(int)infile.length();
       infstrm = new
FileInputStream(infile);
       stmt = conn.createStatement();
       key = (key +1);
       stmt.executeUpdate("insert
into blobtable "
                                    
+ "values(" + key + ", empty_blob())");
       stmt.execute("commit");
       System.out.println("Insert
empty blob successful");
       stmt = conn.createStatement();
       ResultSet rset
= stmt.executeQuery("select binarydata from blobtable "
                                      
+ "where key_id = " + key + " for update");
       System.out.println("Select
executed");
       while(rset.next()){
         myblob = ((OracleResultSet)rset).getBLOB(1);
         bufsize = myblob.getChunkSize();
         byte[] buffer
= new byte[bufsize];
         outstrm =
myblob.getBinaryOutputStream();
         long starttime
= System.currentTimeMillis();
 
         while((len
= infstrm.read(buffer)) != -1){
          outstrm.write(buffer,
0, len);
         }
         long endtime
= System.currentTimeMillis();
         
         System.out.println("Elapse
time to load blob "
                             +
(endtime - starttime)/1000 + " seconds");
       }
       infstrm.close();
       outstrm.close();
    }
    catch(Exception e){
      System.out.println("Input
Operation failed.");
      e.printStackTrace();
    }
 
    try{
       outfile
= new File(outfilePath);
       FileOutputStream
outfstrm = new FileOutputStream(outfile);
       ResultSet rset
= stmt.executeQuery("select binarydata from blobtable where key_id = 1001");
       System.out.println("Select
successful");
       while (rset.next()){
          myblob =((OracleResultSet)rset).getBLOB("binarydata");
          System.out.println("Get
Blob successful.");
          InputStream
istrm = myblob.getBinaryStream();
          int strmdata;
          while((strmdata
= istrm.read()) != -1)
            outfstrm.write(strmdata);
       }
       System.out.println("
Program completed");
       stmt.execute("commit");
       outfstrm.close();
       stmt.close();
       conn.close();
    }
    catch(Exception e){
      System.out.println("Fetch
operation failed");
      e.printStackTrace();
    }
 
  }
}
 
 

 

 

Disclaimer

EXCEPT WHERE
EXPRESSLY PROVIDED OTHERWISE, THE INFORMATION, SOFTWARE,
PROVIDED ON AN "AS IS" AND "AS AVAILABLE"
BASIS. ORACLE EXPRESSLY DISCLAIMS
ALL WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING,
BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR
PURPOSE AND NON-INFRINGEMENT. ORACLE MAKES NO WARRANTY THAT:
(A) THE RESULTS
THAT MAY BE OBTAINED FROM THE USE OF THE SOFTWARE WILL BE ACCURATE OR
RELIABLE; OR (B) THE INFORMATION, OR OTHER MATERIAL OBTAINED
WILL MEET YOUR
EXPECTATIONS. ANY CONTENT, MATERIALS, INFORMATION OR SOFTWARE
DOWNLOADED OR
OTHERWISE OBTAINED IS DONE AT YOUR OWN DISCRETION AND RISK.
ORACLE SHALL HAVE
NO RESPONSIBILITY FOR ANY DAMAGE TO YOUR COMPUTER SYSTEM
OR LOSS OF DATA THAT
RESULTS FROM THE DOWNLOAD OF ANY CONTENT, MATERIALS, INFORMATION
OR SOFTWARE.
 
ORACLE RESERVES THE RIGHT TO MAKE CHANGES OR UPDATES TO THE
SOFTWARE AT ANY
TIME WITHOUT NOTICE.

 

Limitation of Liability

IN NO EVENT
SHALL ORACLE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL OR CONSEQUENTIAL DAMAGES, OR DAMAGES FOR LOSS OF
PROFITS, REVENUE,
DATA OR USE, INCURRED BY YOU OR ANY THIRD PARTY, WHETHER
IN AN ACTION IN
CONTRACT OR TORT, ARISING FROM YOUR ACCESS TO, OR USE OF,
THE SOFTWARE.
 
SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION
OF LIABILITY.
ACCORDINGLY, SOME OF THE ABOVE LIMITATIONS MAY NOT APPLY TO YOU.

 

 

 

 

.
-------------------------------------------------------------------------------------------

Ceara' Java User Group



  Para cancelar sua assinatura, envie um e-mail para: [EMAIL PROTECTED]

  Para mais informacoes, mande um e-mail para: [EMAIL PROTECTED]

  Falar com o administrador? e-mail para: [EMAIL PROTECTED] 

 

Responder a