Primefaces graphicImage не обновляется с помощью ajax - PullRequest
0 голосов
/ 18 мая 2018

Использование Primefaces 6.0 с Glassfish Server 4.0 и JSF2.2 Я хочу иметь возможность добавлять и удалять несколько изображений, используя p: fileUpload.Add работает нормально, но когда я пытаюсь удалить изображение с помощью commandButton с ajax, логика прекрасно работает в компоненте поддержки.Проверено это с помощью отладчика.Но что касается страницы, то graphicImage не обновляется с последними изображениями.
Соответствующий код для моей страницы jsf выглядит следующим образом:

                <h:form id="tempForm" enctype="multipart/form-data">

                <h:panelGroup id="graphicImageCustomerPicturePanel" >
                    <div class="card">
                        <p:panelGrid columns="2" columnClasses="ui-grid-col-6,ui-grid-col-6" 
                                     layout="grid" styleClass="ui-panelgrid-blank form-group" 
                                     style="border:0px none; background-color:transparent;">

                            <c:forEach var="entry" items="#{tempBean.hm2}">
                                <h:panelGroup >
                                    <!-- Right colum -->

                                    <p:commandLink>

                                        <p:graphicImage style="height: 280px; width: 280px; margin-right: 10px;" title="#{entry.value.name}"
                                                        value="#{entry.value}" stream="false" cache="false"/>

                                        <p:ajax event="click" listener="#{tempBean.handlePictureSelect(entry.value.name)}" process="@this" 
                                                update="dlg"  />
                                    </p:commandLink>

                                    <p:commandButton value="Remove" ajax="true" actionListener="#{tempBean.removePicture(entry.key)}"  
                                                     update="graphicImageCustomerPicturePanel" style="width: 280px"/>
                                </h:panelGroup>
                            </c:forEach>

                        </p:panelGrid>

                        <p:fileUpload auto="true" mode="advanced" update="graphicImageCustomerPicturePanel" 
                                      fileUploadListener="#{tempBean.handleFileUploadCustomerPicture}" required="false"
                                      requiredMessage="File Should not be empty!"
                                      id="pictureUploadCustomerPicture" value="#{tempBean.uploadedFileCustomerPicture}"  > 

                        </p:fileUpload>
                        <p:commandButton value="Save Pictures" action="#{tempBean.savePictures('save')}" ajax="false"> 
                            <f:param name="reportTitle" value="Manage Customers" />
                        </p:commandButton>

                        <p:commandButton value="Update Pictures" action="#{tempBean.savePictures('update')}" ajax="false"> 
                            <f:param name="reportTitle" value="Manage Customers" />
                        </p:commandButton>
                    </div>
                </h:panelGroup>
            </h:form>

Код управляемого бина выглядит следующим образом:

private LinkedHashMap<String, InputStream> hm1, prevHm1;
private LinkedHashMap<String, DefaultStreamedContent> hm2;

public void removePicture(String filename) {
    hm1.remove(filename);
    hm2.remove(filename);

    try {

        LinkedHashMap<String, DefaultStreamedContent> tempHm2 = new LinkedHashMap<>();
        Iterator<String> it = hm1.keySet().iterator();
        while(it.hasNext()) {
            String key = it.next();

            InputStream tempIs = hm1.get(key);
            ArrayList a = cloneInputStreamAndDefaultStreamedContent(tempIs);

            if (a != null && a.size() == 2) {
                InputStream is = (InputStream) a.get(0);
                DefaultStreamedContent dsc = (DefaultStreamedContent) a.get(1);
                dsc.setName(key);

                tempHm2.put(key, dsc);
                hm1.put(key, is);
            }
        }
        hm2 = new LinkedHashMap<>(tempHm2);            
    } 
    catch(IOException e) {}
}

public void handleFileUploadCustomerPicture(FileUploadEvent event) {
    try {
        final UploadedFile uploadedFile = event.getFile();
        String filename = uploadedFile.getFileName();

        Iterator<Map.Entry<String, InputStream>> it = hm1.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, InputStream> et = it.next();

            String key = et.getKey();

            ArrayList a = cloneInputStreamAndDefaultStreamedContent(et.getValue());

            if (a != null && a.size() == 2) {
                InputStream is = (InputStream) a.get(0);
                DefaultStreamedContent dsc = (DefaultStreamedContent) a.get(1);
                dsc.setName(key);

                et.setValue(is);

                hm2.put(key, dsc);
            }

        }

        ArrayList a = cloneInputStreamAndDefaultStreamedContent(uploadedFile.getInputstream());
        if (a != null && a.size() == 2) {
            InputStream is = (InputStream) a.get(0);
            DefaultStreamedContent dsc = (DefaultStreamedContent) a.get(1);

            if (hm1.containsKey(filename)) {
                String fn = filename.substring(0, filename.lastIndexOf("."));
                String ext = filename.substring(filename.lastIndexOf("."));
                fn = getNewFilename(fn, ext);
                filename = fn;
            }
            dsc.setName(filename);

            hm1.put(filename, is);
            hm2.put(filename, dsc);
        }
    } catch (IOException e) {
        Cm.setErrorMessage("Error: Owner Customer Picture not uploaded. Please try again later!");
    }
}

public byte[] getByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[8192];
    int len;
    while ((len = input.read(buffer)) > -1) {
        baos.write(buffer, 0, len);
    }
    baos.flush();
    return baos.toByteArray();
}

public ArrayList cloneInputStreamAndDefaultStreamedContent(InputStream pis) throws IOException {
    ArrayList a = new ArrayList();

    InputStream is = null;
    DefaultStreamedContent dsc = null;
    byte[] b = getByteArray(pis);
    is = new ByteArrayInputStream(b);
    pis = new ByteArrayInputStream(b);

    if (pis != null) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = pis.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        dsc = new DefaultStreamedContent(new ByteArrayInputStream(bos.toByteArray()), "image/png");
    }

    a.add(is);
    a.add(dsc);

    return a;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...