Update graphicImage after fileupload

Asked

Viewed 266 times

1

I am trying to update the photo form when I send the image through the dialog via fileupload. The photo only appears after I press F5.

<h:form id="form">

    <h:inputHidden id="idPessoa" value="#{pessoaBean.pessoa.idPessoa}" />
    <h:inputHidden id="codRef" value="#{pessoaBean.pessoa.codRef}" />
    <h:inputHidden id="nomeFoto" value="#{pessoaBean.pessoa.nomeFoto}" />

    <div class="padrao_titulo">Cadastro de Pessoas</div>
    <div class="padrao_botoes_form">
        <p:outputPanel layout="block">

            <p:commandButton value="Voltar" immediate="true" ajax="false"
                icon="ui-icon-arrow-1-w" action="#{pessoaBean.cancelar}" />

            <p:commandButton value="Salvar" action="#{pessoaBean.salvar}"
                ajax="false" icon="ui-icon-disk" />

        </p:outputPanel>
    </div>

    <p:tabView>
        <p:tab title="Dados Pessoais">
            <p:fieldset style="margin-bottom:20px">

                <h:panelGrid columns="2">
                    <p:panelGrid styleClass="noGridBorder">
                        <p:row>
                            <p:column>
                                <p:graphicImage url="#{pessoaBean.retornaFoto()}"
                                    height="120" width="100" />


                                <p:dialog header="Enviar foto" width="750" height="250"
                                    widgetVar="dlgfoto" resizable="false" modal="true"
                                    appendTo="@(body)" closable="true" draggable="false"
                                    closeOnEscape="true">

                                    <h:form id="formFoto" enctype="multipart/form-data">
                                        <p:fileUpload fileUploadListener="#{pessoaBean.upload}"
                                            fileLimit="1" update=":form:nomeFoto" required="true"
                                            requiredMessage="O campo Foto é obrigatório."
                                            fileLimitMessage="Excedido Limite de arquivos"
                                            cancelLabel="Cancelar" label="Procurar"
                                            uploadLabel="Anexar"
                                            invalidSizeMessage="Tamanho excedido(200kb)"
                                            sizeLimit="204800"
                                            invalidFileMessage="Somente arquivos .jpg, .png ou .gif"
                                            allowTypes="/(\.|\/)(gif|jpe?g|png)$/" mode="advanced"
                                            skinSimple="true" />
                                        <!-- <p:commandButton value="Enviar" ajax="false" /> -->
                                    </h:form>
                                </p:dialog>
                            </p:column>
                        </p:row>

                        <p:row>
                            <p:column style="text-align: center">
                                <p:commandButton icon="ui-icon-person" value="Foto"
                                    onclick="PF('dlgfoto').show();" for="foto" />
                            </p:column>
                        </p:row>

                        <br />
                    </p:panelGrid>

                    .....

                </h:panelGrid>
            </p:fieldset>
    </p:tab>

    </p:tabView>

</h:form>

Personal @requestscope

public String retornaFoto() {
    HttpServletRequest url = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String urlBase = url.getRequestURL().toString().substring(0, (url.getRequestURL().toString().length() - url.getServletPath().length()));

    if (this.pessoa != null) {
        if (this.pessoa.getNomeFoto() != null) {
            return urlBase + "/fotos/" + this.pessoa.getNomeFoto();
        } else {
            return urlBase + "/resources/img/avatar_100.png";
        }
    }
    return urlBase + "/resources/img/avatar_100.png";
}


public void upload(FileUploadEvent event) {
    try {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        @SuppressWarnings("unused")
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

        FacesContext aFacesContext = FacesContext.getCurrentInstance();
        ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();

        String realPath = context.getRealPath("/");

        // Aqui cria o diretorio caso não exista
        File file = new File(realPath + "/fotos//");
        if (!file.exists()) {

            file.mkdirs();
        }

        byte[] arquivo = event.getFile().getContents();
        String caminho = realPath + "\\fotos\\" + event.getFile().getFileName();
        String nomeFoto = event.getFile().getFileName();
        // esse trecho grava o arquivo no diretório
        FileOutputStream fos = new FileOutputStream(caminho);
        fos.write(arquivo);
        fos.close();

        this.pessoa.setNomeFoto(nomeFoto);



        System.out.println("Arquivo: " + arquivo);
        System.out.println("Caminho da imagem: " + caminho);
        System.out.println("Nome da imagem: " + nomeFoto);
        System.out.println("CAminho imagem 2: " + file + "\\" + this.pessoa.getNomeFoto());



        //MetodosUtil.criarAviso("Foto processada!");
        MetodosUtil.executarJavaScript("PF('dlgfoto').hide();");
    } catch (Exception ex) {
        System.out.println("Erro no upload de imagem" + ex);
    }

}
  • Instead of FileOutputStream fos = new FileOutputStream(caminho); fos.write(arquivo); fos.close();, use, if you are in Java 7 or higher, try (FileOutputStream fos = new FileOutputStream(caminho)) { fos.write(arquivo); }. If you’re in Java 6 or below, use FileOutputStream fos = null; try { fos = new FileOutputStream(caminho); fos.write(arquivo); } finally { if (fos != null) fos.close(); } - The reason to do this is to ensure that the file will be closed properly.

1 answer

1

Well, I usually use a script for that. Follows:

<script>
    var loadFile = function (event) {
        var output = document.getElementById('output');
        output.src = URL.createObjectURL(event.target.files[0]);
    };
</script>

Where output id is an element .

The event that will trigger the script will be set in the file upload action. Which event will be fired is up to you. I usually use the onchange.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.