Vaadin上传图像并将其存储到数据库中
问题描述:
我正在使用Vaadin上传组件,到目前为止,我已设法将图像上载到目录,并在成功上载后将其显示在面板组件中。之后我想要做的是将其插入数据库中。我所拥有的名为Show的表格有一个名称,日期和图像。在Show类中,我尝试将图像作为字节数组或Blob。Vaadin上传图像并将其存储到数据库中
Column(name="image")
private byte[] image;
@Lob
@Column(name="image")
private Blob image;
在上传succeded方法我想将文件转换为字节数组,到目前为止,我已经试过这样:
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();
}
我也试过这样:
byte[] data = Files.readAllBytes(new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename()).toPath());
uIP.uploadImage(data);
uIP它实际上是我的uploadImagePresenter,我尝试将字节数组转换为Blob,或者直接将它传递给存储库作为字节数组
public void uploadImage(byte[] data) throws SerialException, SQLException{
//Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
showRepo.updateAfterImage(show, data); // or (show, blob)
}
在我的仓库,在我updateAfterImage方法我有:
public void updateAfterImage(Show show, byte[] data) //or Blob data
{
em.getTransaction().begin(); //em - EntityManager
show.setImage(data);
em.getTransaction().commit();
}
无论是与BLOB或字节数组,我不能管理通过设置它的图像更新现有的节目,并在更新数据库(单元格保持NULL)。我也没有错误来帮助我弄清楚什么是错误的。任何帮助/建议都会有用。谢谢!
答
我找到了解决方案。是什么使它的工作是:
em.getTransaction().begin();
em.find(Show.class, show.getId());
show.setImage(data);
em.merge(spectacol);
em.getTransaction().commit();
在我的updateAfterImage方法在展示存储库。
合并对于更新blob字段没有意义(并非您显示的是什么是“壮观的”)......一旦对象被管理(通过find进行检索),它将在刷新/提交时在数据存储中更新为no其他电话需要 –
我很抱歉,壮观的意思是用我的语言展示,我在发布答案之前忘了翻译它。感谢您的信息! –