0

我觉得这很奇怪,我不知道为什么,但是当我第一次选择图像时,它不会调用上传侦听器,但在第二次选择时它工作得很好。

查看代码:

<h:form enctype="multipart/form-data;charset='UTF-8'">
    <p:fileUpload id="clientProfile" auto="true" sizeLimit="2097152" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" fileUploadListener="#{clientController.uploadListener}" mode="advanced" multiple="true" label="browse" update="imagePreview" invalidFileMessage="Invalid image" invalidSizeMessage="too large size"/>
    <p:outputPanel id="imagePreview">
        <ui:repeat value="#{clientController.listImages}" var="imageId">
            <div style="float:left;margin-right:10px; margin-bottom: 5px;">
                <p:graphicImage value="#{clientController.previewImage}" height="135" width="135" styleClass="images">
                    <f:param name="imageId" value="#{imageId}"/>
                </p:graphicImage>
            </div>
        </ui:repeat>
    </p:outputPanel>
</h:form>

豆代码:

private Map<UUID, UploadedFile> uploadedFiles = new HashMap<UUID, UploadedFile>();//used for preview
  private List<String> listImages = new ArrayList<String>(); //list of id from map which is UUID
 private List<UploadedFile> clientProfile = new ArrayList<UploadedFile>();


public void uploadListener(FileUploadEvent event) {
    clientProfile.add(event.getFile());
    final UUID uuid = UUID.randomUUID();
    uploadedFiles.put(uuid, event.getFile());
    listImages.add(uuid.toString());
    System.out.println(listImages.size());
    System.out.println(clientProfile.size());
  }

  public List<String> getListImages() {
    return listImages;
  }

  public StreamedContent getPreviewImage() {
    FacesContext context = FacesContext.getCurrentInstance();
    if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
      return new DefaultStreamedContent();
    } else {
      StreamedContent image = null;
      String imageId = JsfUtil.getRequestParameter("imageId");
      System.out.println(imageId);
      if (imageId != null) {
        UUID imageIndex = UUID.fromString(imageId);
        return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFiles.get(imageIndex).getContents()));
      }
    }
    return null;

  }
4

0 回答 0