Problem with FileUpload

3

I had the opportunity to find an application ready on the internet as shown below:

link

But I'm new to the Java programmer, I tried to adapt the application my way, but I was not successful.

Application has to add the name, value and image all in one entity, when the user adds the record the application manages to save all the data including the image in the database, but when it is for screen shows it generates a problem, take a look at the image below.

Thisimagewiththenametest333wasnotforappears,Ihadincludedanotherimage.Butwhydidthisimageappearthere?

BecauseIhadaddeditinalasttest,butitwasnottoappearintheregistryofthenametest333,itwastobeanotherimage.

WhenIaddedthefourthrecordthishappened:

He put the images in the correct order and did not show the last image.

I believe the error is in this method.

public void processFileUpload(FileUploadEvent uploadEvent) {

    try {

        ServletContext sContext = (ServletContext) FacesContext
                .getCurrentInstance().getExternalContext().getContext();

        File folder = new File(sContext.getRealPath("/temp"));
        if (!folder.exists())
            folder.mkdirs();

        for (Produto f : produtos) {
            String nomeArquivo = f.getId() + ".jpg";
            String arquivo = sContext.getRealPath("/temp") + File.separator
                    + nomeArquivo;

            criaArquivo(f.getImagem(), arquivo);
        }
        produto.setImagem(uploadEvent.getFile().getContents());
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

The problem is logical and I'm in need of help to correct the logic.

This is my page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">

<h:head>
    <style type="text/css">
.ui-widget {
    font-size: 11px !important;
    font-family: Verdana, Arial, Tahoma;
    font-weight: light;
}
</style>
</h:head>

<h:body>

    <p:ajaxStatus
        style="width:64px;height:64px;position:fixed;right:5px;bottom:5px">
        <f:facet name="start">
            <p:graphicImage value="/images/loading.gif" />
        </f:facet>

        <f:facet name="complete">
            <h:outputText value="" />
        </f:facet>
    </p:ajaxStatus>

    <h:form id="form" enctype="multipart/form-data">
        <p:growl id="msgs" showDetail="false" showSummary="true" />

        <p:panel>
            <h:panelGrid columns="2">
                <h:outputText value="Nome:" />
                <p:inputText value="#{mbProduto.produto.nome}" />

                <h:outputText value="Preço:" />
                <p:inputText value="#{mbProduto.produto.preco}" />

                <h:outputText value="Foto: " />
                <p:fileUpload fileUploadListener="#{mbProduto.processFileUpload}"
                    label="Escolher" cancelLabel="Cancelar" sizeLimit="400000"
                    invalidSizeMessage="Imagem muito grande" auto="true"
                    invalidFileMessage="Tipo de imagem não suportado"
                    allowTypes="/(\.|\/)(jpe?g|png)$/" />



                <p:commandButton value="Salvar" action="#{mbProduto.salvaProduto()}"
                    update=":form:msgs, :form:dtProdutos, :form" />
                <p:commandButton value="Limpar" onclick="form.reset()" />
            </h:panelGrid>
        </p:panel>

        <p:dataTable id="dtProdutos" value="#{mbProduto.produtos}" var="p"
            style="text-align: center;" emptyMessage="Nenhum produto cadastrado.">
            <p:column headerText="ID" style="width:2%; font-weight: bold;">
                <h:outputText value="#{p.id}" />
            </p:column>

            <p:column headerText="Nome" style="width:14%">
                <h:outputText value="#{p.nome}" />
            </p:column>

            <p:column headerText="Preço" style="width:14%">
                <h:outputText value="#{p.preco}" />
            </p:column>
            <p:column headerText="foto" style="width:24%">
                <p:graphicImage value="/temp/#{p.id}.jpg" cache="false" width="100"
                    height="50" />
            </p:column>
        </p:dataTable>


    </h:form>
</h:body>
</html>
    
asked by anonymous 27.05.2015 / 14:06

2 answers

1

The image did not change because you recorded another image with the same name, so the browser uses the image that is cached. One trick to always update the image is to place a random text as a parameter after the image, for example the current date:

<p:graphicImage value="/temp/#{p.id}.jpg?#{data_atual}" cache="false" width="100" height="50" />

In the above code ? indicates that the following are parameters and current_data is any one variable for example one containing new Date (). Although I think cache="false" should no longer cache, it might be a bug.

According to your code it looks like an image is being created in a temporary folder and writing the bits in the database. In the form of your code the displayed image is the one in the temporary folder. To load the bank should make some adjustments:

In the Product class:

public StreamedContent getImagem() throws IOException {
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(this.imagem);
        File file = new File("imagem");
        ImageIO.write(img, "jpg", file);
        FileInputStream fi = new FileInputStream(file);
        return new DefaultStreamedContent(fi);
    }

On the screen:

<p:graphicImage value="#{mbProduto.produto.imagem}" width="100" height="50" />
    
26.06.2015 / 20:37
1

I've already gone through this and it was not wrong in the code, but the version of primefaces that I was using the component p:graphicImage did not update trying to update in primefaces version.     

26.06.2015 / 18:09