0

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 在会话范围内。

4

1 回答 1

4

您正在尝试读取InputStream两次(第一次是在DefaultStreamedContent上传方法的构造函数中,第二次是在保存方法的复制循环中)。这是不可能的。它只能读取一次。您需要byte[]先将其读入,然后将其分配为 bean 属性,以便您可以将其重用于 theStreamedContent和 save。

确保您从不持有外部资源,例如InputStreamOutputStream作为 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>.

于 2012-12-04T13:55:17.767 回答