【发布时间】:2011-11-01 06:04:29
【问题描述】:
希望你们一切都好。实际上我想将图像文件从系统上传到数据库。但是我希望当用户上传文件时文件没有直接进入数据库,而是在选择文件之后。文件可能会保存到某个临时位置,所以当用户点击保存按钮时,我会将所有图像移动到数据库。我正在使用 JSF 2.0 和 PrimeFaces。我在某人的博客上找到了代码。代码的作用是在上传文件后,将其转换为 byte[] 数组。我将该字节数组保存在一个列表中,所以点击保存按钮我从列表中获取图像。
这里是代码
private StreamedContent image;
public StreamedContent getImage() {
return image;
}
public void setImage(StreamedContent image) {
this.image = image;
}
public String imageUpload(FileUploadEvent event) {
try {
// Convert file from input stream to bytes
byte[] byteArray = InputStreamToByte(event.getFile().getInputstream());
/**
* Add images to list so we can retrieve them when user click on save button
*/
boolean add = images.add(new Images(byteArray));
/**
* Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://x.x.x.x:5432/MYDB";
Connection oConnection = DriverManager.getConnection(url, "username", "password");
System.out.println("Sucessfully connected to Postgres Database");
*
* byte[] bytes = bos.toByteArray();
String sql = "INSERT INTO my_table (byte_array) VALUES (?)";
statement = oConnection.prepareStatement(sql);
statement.setBytes(1, bytes);
statement.executeUpdate();
System.out.println("Image inserted into database!");
*/
//byteArray used to store picture into database
InputStream ist = new ByteArrayInputStream(byteArray);
/*
* StreamedContent Object used to show the picture in jsf pages. We need to convert
* again bytearray to InputStream
*/
image = new DefaultStreamedContent(ist, "image/jpg");
FacesMessage msg = new FacesMessage("Succesful picture is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
//we dont need to use faces-config to navigate in jsf 2
return null ;
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Exception happen");
FacesContext.getCurrentInstance().addMessage(null, msg);
e.printStackTrace();
return null;
}
} //end of imageUpload()
这是我的 .html 文件
<h:panelGrid width="30%" columns="3">
<h:outputText value="Map to upload" />
<p:fileUpload id="uploadFile"
description="Image"
update="messages"
allowTypes="*.jpg;*.png;*.gif;*.jpeg;"
auto="true"
fileUploadListener=#{cityDetail.imageUpload} >
<f:ajax event="????" execute="???" render="uploadedInage" />
</p:fileUpload>
<p:graphicImage id="uploadedImage"
value="#{cityDetail.image}"
</h:panelGrid>
现在我希望当图像完全上传后,图像也会显示在面板网格的第 3 列。为此,我正在尝试使用 Ajax。但我不知道我应该使用什么事件。所以请任何人告诉我事件名称并且我想要求执行我应该使用“@this”吗? .还告诉我,我的方法是正确的,将二进制图像保存在列表中,这样当用户单击保存按钮时,我会检索所有图像并将它们发送到数据库。出于我的目的,在这里也使用 Ajax 是正确的想法吗?
谢谢
【问题讨论】:
标签: jsf-2