我试图将图像文件上传到数据库。在保存图像之前,我想将其显示给用户。
我有一个请求范围的bean,UserInfoBean
(我无法改变请求范围)我试图用来保存数据,但是preview
字节[调用paint时,为null。有没有办法能够保存preview
或image
,在调用paint()时要访问的UploadItem?
info.xhtml代码:
<a4j:outputPanel id="preview"
<a4j:mediaOutput id="imgPreview"
element="img"
mimeType="image/jpeg"
createContent="#{userInfo.paint}"
cacheable="false"
style="width:150px; height:100px;" />
<br/>
</a4j:outputPanel>
<a4j:outputPanel id="signatureStampDisplay">
<br/>
<rich:fileUpload fileUploadListener="#{userInfo.uploadImage}"
id="upload"
listHeight="40px"
acceptedTypes="#{userInfo.supportedTypes}"
ontyperejected="alert('Only JPG, GIF, PNG, BMP, and TIF files are accepted');"
maxFilesQuantity="1"
immediateUpload="true"
autoclear ="true"
disabled="#{userInfo.stampSet}">
<a4j:support event="onuploadcomplete"
limitToList="true"
reRender="preview"/>
</rich:fileUpload>
</a4j:outputPanel>
UserInfoBean的一部分,包含UploadItem
图片和byte[]
预览:
public void uploadImage(UploadEvent evt) throws IOException{
image = evt.getUploadItem();
if(image != null){
//preview is a byte[]
preview = FileUtils.readFileToByteArray(image.getFile());
}
}
public void paint(OutputStream stream, Object object) throws IOException{
if(preview != null){
stream.write(preview);
}
}
答案 0 :(得分:0)
由于bean是请求范围,因此无法传递。
使用HttpSession对象javax.servlet.http.HttpSession;
我能够在需要时存储字节[] preview
,在paint
public void uploadImage(UploadEvent evt) throws IOException{
image = evt.getUploadItem();
if(image != null){
preview = FileUtils.readFileToByteArray(signature.getFile());
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
session.setAttribute("preview", preview);
}
}
public void paint(OutputStream stream, Object object) throws IOException{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
preview = (byte[]) session.getAttribute("preview");
if(preview != null){
stream.write(preview);
stream.close();
session.removeAttribute("preview");
signaturePreview = null;
}
}