How to save an image in SQLServer 2014 from Java using JPA?

0

I am trying to save an image that is selected from a user interface using the following code:

private void botonSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {                                                 
    // TODO add your handling code here:       
    JFileChooser escogerArchivo = new JFileChooser();
    if (escogerArchivo.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        archivo = escogerArchivo.getSelectedFile();
        ImageIcon temporal = new ImageIcon(archivo.getAbsolutePath());
        ImageIcon imagen = new ImageIcon(temporal.getImage().getScaledInstance(
                this.etiquetaFoto.getWidth(),
                this.etiquetaFoto.getHeight(),
                Image.SCALE_DEFAULT));
        this.etiquetaFoto.setIcon(imagen);
        this.setArchivo(archivo);
    } 
}

Where at the end, I make a setArchivo (), so that the selected image is saved in a parameter of the class called file, of type File. The problem is that I do not find a reasonable way to store that file in SQL. In SQl I have a column called image of type image and I understand that it will be saved in byte format [], but how do I get the bytes of the selected file and how would I read the bytes of SQL to show it in the same interface? ?

    
asked by David Antonio Hermosillo Solis 26.11.2017 в 18:12
source

1 answer

0

Here is an example I made a while ago and it works correctly for me. This is for MySQL. But you can adapt it to any database.

    public void guardar_imagen_BD(Connection con, String archivo){

            File imagen = null;
            PreparedStatement preparado = null;
            FileInputStream fis = null;
            String nombre_archivo=null;

    try {

            imagen =  new File(archivo);

            if(imagen.getName().substring(0, imagen.getName().length()-4).length()<=2){//si tiene el nombre dos caracteres o menos se le inventa uno automatico
                    nombre_archivo="auto"+Math.random();}//se genera un rombre aleatorio
            else   { nombre_archivo=imagen.getName().substring(0, imagen.getName().length()-4);}//se mantiene el nombre real

            fis = new FileInputStream(imagen);
            preparado = con.prepareStatement("INSERT INTO control_de_estudio.fotos VALUES (?,?)");
            preparado.setString(1, nombre_archivo);
            preparado.setBinaryStream(2, fis,(int)imagen.length());
            preparado.executeUpdate();

        } catch (SQLException ex) {
            Logger.getLogger(imagenes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(imagenes.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                 con.close();
                 fis.close();

            } catch (SQLException ex) {
                Logger.getLogger(imagenes.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(imagenes.class.getName()).log(Level.SEVERE, null, ex);
            }


        }

}

Remember to declare the field of the Blob-type image in the database.

    
answered by 27.11.2017 в 22:19