Uploading and Downloading Files( Binary Data) in DB

0


Converting File into Binary and Inserting into DB 

package basics;


import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Main {
  static String url = "jdbc:oracle:thin:@localhost:1521:Oracle12c";
  static String username = "data";
  static String password = "xxxxxx";

  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);

    String sql = "INSERT INTO documentuploads(name, description, doc_name) VALUES (?, ?, ?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "my.xlsm");
    stmt.setString(2, "Excel File");

    File image = new File("C:\\Users\\XXXX\\Documents\\New_ID_BMM_PCMT-GCW_WORKBOOK_Name.xlsm");
    FileInputStream   fis = new FileInputStream(image);
    stmt.setBinaryStream(3, fis, (int) image.length());
    stmt.execute();

    conn.commit();
    fis.close();
    conn.close();
    System.out.println("OkOk");
  }
}


Retrieving Blob and Converting to File:

package basics;
import java.sql.*;  
import java.io.*;  
public class RetrieveImage {

public static void main(String[] args) {
try{  
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:Oracle12c","data","xxxxx");  
     
PreparedStatement ps=con.prepareStatement("select * from documentuploads where name='From Talend'");  
ResultSet rs=ps.executeQuery();  
int i=1;
while (rs.next()){
             
Blob b=rs.getBlob(3);   // third column
byte barr[]=b.getBytes(1,(int)b.length());  
             
FileOutputStream fout=new FileOutputStream("e:\\TalendOut"+i+"_.jpg");  
fout.write(barr);  
             
fout.close();  
i++;
}//end of if  
System.out.println("ok");  
             
con.close();  
}catch (Exception e) {e.printStackTrace();  }  

}

}


Converting File to Byte Array :

 package basics ;
 public class FileRead {
 
public static byte[] ByteArrayFromFile(String filepath) {
try{
java.io.File file=new java.io.File(filepath);
java.io.FileInputStream fis = new java.io.FileInputStream(file);
int fileLength = (int) file.length();
byte[] incoming_file_data = new byte[fileLength]; // allocate byte array of right size
fis.read(incoming_file_data, 0, fileLength ); // read into byte array
fis.close();
return incoming_file_data;
}catch(Exception err){
err.printStackTrace();return null;
}
}
}