Christina.keri
Christina.keri

Reputation: 11

Vaadin upload image and store it to database

I am using a Vaadin upload component and so far I have managed to upload an image to a directory, and display it in a panel component after it is successfull uploaded. What I want to do after this, is to insert it in the database aswell. What I have is a table called Show which has a name, date and an image. In the Show class I have tried to have my image as a byte array or as a Blob.

Column(name="image")
private byte[] image;

@Lob
@Column(name="image")
private Blob image;

In the upload succeded method I want to convert the file to a byte array, and so far I have tried this:

File file = new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename());
byte[] bFile = new byte[(int) file.length()];
try {
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    uIP.uploadImage(bFile);
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

I tried also this:

byte[] data = Files.readAllBytes(new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename()).toPath());
uIP.uploadImage(data);

uIP it is actually my uploadImagePresenter, where I tried to transform the byte array to Blob, or simply pass it to the repository as byte array

 public void uploadImage(byte[] data) throws SerialException, SQLException{
    //Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
    showRepo.updateAfterImage(show, data);         // or (show, blob)
}

In my repository, in my updateAfterImage method I have:

public void updateAfterImage(Show show, byte[] data)             //or Blob data
{
     em.getTransaction().begin();                       //em - EntityManager
     show.setImage(data);
     em.getTransaction().commit();
}

Either with Blob or a byte array, I can't manage to update the existing show by setting its image and update it in the database (the cell remains NULL). Also I get no error to help me figure out what is going wrong. Any help/advice would be useful. Thanks!

Upvotes: 0

Views: 897

Answers (1)

Christina.keri
Christina.keri

Reputation: 11

I have found the solution. What made it work was:

em.getTransaction().begin(); 
em.find(Show.class, show.getId()); 
show.setImage(data); 
em.merge(spectacol); 
em.getTransaction().commit();

in my updateAfterImage method in the show repository.

Upvotes: 0

Related Questions