Problem with Fileupload

Asked

Viewed 496 times

3

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

https://github.com/wladyband/Produtos/blob/master/Produtos/src/com/wordpress/programandojava/controller/ProdutoBean.java

But I’m new as a Java programmer, I tried to adapt the application my way, but I didn’t succeed.

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

inserir a descrição da imagem aqui

This image with the name of teste333 was not to appear, I had included another image. But because this image appeared there?

Because I had added it in one last test, but it was not to appear in the registration of the name test333, it was to be another image.

When I added the fourth record this happened:

inserir a descrição da imagem aqui

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

I believe the error lies 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 need 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>

2 answers

1

Friend I’ve been through this and it wasn’t anything wrong with the code but the version of primefaces that I was using the componomente p:graphicImage did not update try to do update in the version of primefaces.

1

The image did not change because you saved another image with the same name, so the browser uses the image that is cached. A trick to always update the image is to put a random text as 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 code above ? indicates that the following are parameters and data_current is any variable for example one containing new Date(). Although I think cache="false" should no longer cache, maybe it’s a bug.

According to your code it seems that an image is being created in a temporary folder and saving the bits in the database. In the form of your code the image displayed is the one in the temporary folder. To load from the database some adjustments should be made:

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);
    }

Onscreen:

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

Browser other questions tagged

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