当我要保存上传的图片时,我正在Stream is closed Exception
。
我想在保存之前预览上传图片的graphicImage
。此操作正在运行。但我无法保存图像。这是我的代码:
private InputStream in;
private StreamedContent filePreview;
// getters and setters
public void upload(FileUploadEvent event)throws IOException {
// Folder Creation for upload and Download
File folderForUpload = new File(destination);//for Windows
folderForUpload.mkdir();
file = new File(event.getFile().getFileName());
in = event.getFile().getInputstream();
filePreview = new DefaultStreamedContent(in,"image/jpeg");
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void setFilePreview(StreamedContent fileDownload) {
this.filePreview = fileDownload;
}
public StreamedContent getFilePreview() {
return filePreview;
}
public void saveCompanyController()throws IOException{
OutputStream out = new FileOutputStream(getFile());
byte buf[] = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
FileMasterDO fileMasterDO=new FileMasterDO();
fileMasterDO.setFileName(getFile().getName());
fileMasterDO.setFilePath(destination +file.getName());
fileMasterDO.setUserMasterDO(userMasterService.findUserId(UserBean.getUserId()));
fileMasterDO.setUpdateTimeStamp(new Date());
in.close();
out.flush();
out.close();
fileMasterService.save(filemaster);
}
bean在会话范围内。
答案 0 :(得分:4)
您尝试读取InputStream
两次(第一次是在DefaultStreamedContent
上传方法的构造函数中,第二次是在save方法的复制循环中)。这是不可能的。它只能读一次。您需要先将其读入byte[]
,然后将其指定为bean属性,以便可以将其重用于StreamedContent
和保存。
确保永远保留外部资源,例如InputStream
或OutputStream
作为bean属性。从适用的当前和其他bean中删除它们,并使用byte[]
将图像的内容保存为属性。
在您的特定情况下,您需要按如下方式修复它:
private byte[] bytes; // No getter+setter!
private StreamedContent filePreview; // Getter only.
public void upload(FileUploadEvent event) throws IOException {
InputStream input = event.getFile().getInputStream();
try {
IOUtils.read(input, bytes);
} finally {
IOUtils.closeQuietly(input);
}
filePreview = new DefaultStreamedContent(new ByteArrayInputStream(bytes), "image/jpeg");
// ...
}
public void saveCompanyController() throws IOException {
OutputStream output = new FileOutputStream(getFile());
try {
IOUtils.write(bytes, output);
} finally {
IOUtils.closeQuietly(output);
}
// ...
}
注意:IOUtils
来自Apache Commons IO,您应该已经在类路径中拥有它,因为它是<p:fileUpload>
的依赖项。