To save a file to a database, do the following:
public boolean insertFile( File f ){
Connection c = this.getConnection();//busca uma conexao com o banco
try {
PreparedStatement ps = c.prepareStatement("INSERT INTO arquivo( id, nome, arquivo ) VALUES ( nextval('seq_arquivo'), ?, ? )");
//converte o objeto file em array de bytes
InputStream is = new FileInputStream( f );
byte[] bytes = new byte[(int)f.length() ];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
ps.setString( 1, f.getName() );
ps.setBytes( 2, bytes );
ps.execute();
ps.close();
c.close();
return true;
} catch (SQLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return false;
}
Understanding the method: First, convert the file to an array of
bytes (byte []). Then we use the setBytes of the PreparedStatement
to store the file in the specified column.
And that's it: by using this method, we save the name and file itself
in a table in the database.
To recover the file do the following:
public File getFile( int id ){
Connection c = this.getConnection();//busca uma conexao com o banco
File f = null;
try {
PreparedStatement ps = c.prepareStatement("SELECT id, nome, arquivo FROM arquivo WHERE id = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if ( rs.next() ){
byte [] bytes = rs.getBytes("arquivo");
String nome = rs.getString("nome");
//converte o array de bytes em file
f = new File( "/local_a_ser_salvo/" + nome );
FileOutputStream fos = new FileOutputStream( f);
fos.write( bytes );
fos.close();
}
rs.close();
ps.close();
c.close();
return f;
} catch (SQLException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
The procedure is the inverse: it returns the column value in array of
bytes and creates a disk file from these bytes.
If you do not know how to create an object of type File
from a look in the Java documentation that is easy to understand.
Source: link