How to register a photo using Uploadedfile from primefaces? I was able to save the photo inside the photo variable but I can’t save it in the database

Asked

Viewed 1,135 times

-1

Console message:

set 02, 2015 11:05:01 AM com.sun.faces.config.ConfigureListener contextInitialized
INFORMAÇÕES: Inicializando Mojarra 2.2.8 ( 20140814-1418 https://svn.java.net/svn/mojarra~svn/tags/2.2.8@13507) para o contexto '/restaurante'
set 02, 2015 11:05:01 AM com.sun.faces.spi.InjectionProviderFactory createInstance
INFORMAÇÕES: JSF1048: Anotações PostConstruct/PreDestroy presentes.  Os métodos ManagedBeans marcados com essas anotações informarão as anotações processadas.
set 02, 2015 11:05:02 AM org.primefaces.webapp.PostConstructApplicationEventListener processEvent
INFORMAÇÕES: Running on PrimeFaces 5.0
set 02, 2015 11:05:02 AM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["http-nio-8080"]
set 02, 2015 11:05:02 AM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["ajp-nio-8009"]
set 02, 2015 11:05:02 AM org.apache.catalina.startup.Catalina start
INFORMAÇÕES: Server startup in 4091 ms
Hibernate: select produto0_.id as id1_7_, produto0_.categoria_id as categori6_7_, produto0_.image as image2_7_, produto0_.nome as nome3_7_, produto0_.quantidade as quantida4_7_, produto0_.valor as valor5_7_ from Produto produto0_
Hibernate: select categoria0_.id as id1_0_0_, categoria0_.nome as nome2_0_0_ from Categoria categoria0_ where categoria0_.id=?
Hibernate: select categoria0_.id as id1_0_, categoria0_.nome as nome2_0_ from Categoria categoria0_
Hibernate: select categoria0_.id as id1_0_, categoria0_.nome as nome2_0_ from Categoria categoria0_ where categoria0_.id=?
>>>>>>>> uploaed file: org.primefaces.model.NativeUploadedFile@44bda584
Hibernate: insert into Produto (categoria_id, image, nome, quantidade, valor) values (?, ?, ?, ?, ?)
Hibernate: select categoria0_.id as id1_0_, categoria0_.nome as nome2_0_ from Categoria categoria0_

Here on the console I’m printing the photo that was stored in the photo variable but I don’t know how to save it in the bank.

Bean

Classe ProdutoBean:

    package bean;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

import dao.CategoriaDAO;
import dao.ProdutoDAO;
import domain.Categoria;
import domain.Produto;
import util.FacesUtil;

@ManagedBean(name = "produtoBean")
@ViewScoped
public class ProdutoBean implements Serializable {

    private Produto produtoCadastro = new Produto();
    private List<Produto> listaProdutos;
    private List<Produto> listaProdutosFiltrados;

    private String acao;
    private Long codigo;

    private List<Categoria> listaCategoria;

    private UploadedFile foto;

    public UploadedFile getFoto() {
        return foto;
    }

    public void setFoto(UploadedFile foto) {
        this.foto = foto;
    }

    public Produto getProdutoCadastro() {
        return produtoCadastro;
    }

    public void setProdutoCadastro(Produto produtoCadastro) {
        this.produtoCadastro = produtoCadastro;
    }

    public List<Produto> getListaProdutos() {
        return listaProdutos;
    }

    public void setListaProdutos(List<Produto> listaProdutos) {
        this.listaProdutos = listaProdutos;
    }

    public List<Produto> getListaProdutosFiltrados() {
        return listaProdutosFiltrados;
    }

    public void setListaProdutosFiltrados(List<Produto> listaProdutosFiltrados) {
        this.listaProdutosFiltrados = listaProdutosFiltrados;
    }

    public String getAcao() {
        return acao;
    }

    public void setAcao(String acao) {
        this.acao = acao;
    }

    public Long getCodigo() {
        return codigo;
    }

    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    public List<Categoria> getListaCategoria() {
        return listaCategoria;
    }

    public void setListaCategoria(List<Categoria> listaCategoria) {
        this.listaCategoria = listaCategoria;
    }

    public void salvar() {
        try {
            System.out.println(">>>>>>>> uploaed file: " + foto);
            if (foto != null) {
                produtoCadastro.setImage(foto.getContents());
            }

            ProdutoDAO produtoDAO = new ProdutoDAO();
            produtoDAO.salvar(produtoCadastro);

            produtoCadastro = new Produto();

            FacesUtil.adicionarMsgInfo("Produto Cadastrado com sucesso");
        } catch (RuntimeException ex) {
            FacesUtil.adicionarMsgErro("Erro ao incluir o Produto" + ex.getMessage());
        }
    }

    public void novo() {
        produtoCadastro = new Produto();

    }

    public void carregarPesquisa() {
        try {
            ProdutoDAO produtoDAO = new ProdutoDAO();
            listaProdutos = produtoDAO.listar();
        } catch (RuntimeException ex) {
            FacesUtil.adicionarMsgErro("Erro ao listar os Produtos" + ex.getMessage());
        }
    }

    public void carregarCadastro() {
        try {
            if (codigo != null) {
                ProdutoDAO produtoDAO = new ProdutoDAO();
                produtoCadastro = produtoDAO.buscarPorCodigo(codigo);
            } else {
                produtoCadastro = new Produto();
            }
            CategoriaDAO categoriaDAO = new CategoriaDAO();
            listaCategoria = categoriaDAO.listar();
        } catch (RuntimeException ex) {
            FacesUtil.adicionarMsgErro("Erro ao incluir o Produto" + ex.getMessage());
        }
    }

    public void excluir() {
        try {
            ProdutoDAO produtoDAO = new ProdutoDAO();
            produtoDAO.excluir(produtoCadastro);

            FacesUtil.adicionarMsgInfo("Produto excluido com sucesso");
        } catch (RuntimeException ex) {
            FacesUtil.adicionarMsgErro("Erro ao incluir o Produto" + ex.getMessage());
        }
    }

    public void editar() {
        try {
            ProdutoDAO produtoDAO = new ProdutoDAO();
            produtoDAO.editar(produtoCadastro);

            FacesUtil.adicionarMsgInfo("Produto Editado com sucesso");
        } catch (RuntimeException ex) {
            FacesUtil.adicionarMsgErro("Erro ao incluir o Produto" + ex.getMessage());
        }
    }

}

DAO

package dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import domain.Produto;
import util.HibernateUtil;

public class ProdutoDAO {
    public void salvar(Produto produto) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;

        try {
            transacao = sessao.beginTransaction();
            sessao.save(produto);
            transacao.commit();
        } catch (RuntimeException ex) {
            if (transacao != null) {
                transacao.rollback();
            }
            throw ex;
        } finally {
            sessao.close();
        }
    }

    @SuppressWarnings("unchecked")
    public List<Produto> listar() {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        List<Produto> produtos = null;

        try {
            Query consulta = sessao.getNamedQuery("Produto.listar");
            produtos = consulta.list();
        } catch (RuntimeException ex) {
            throw ex;
        } finally {
            sessao.close();
        }
        return produtos;
    }

    public Produto buscarPorCodigo(Long id) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Produto produto = null;

        try {
            Query consulta = sessao.getNamedQuery("Produto.buscarPorCodigo");
            consulta.setLong("id", id);

            produto = (Produto) consulta.uniqueResult();
        } catch (RuntimeException ex) {
            throw ex;
        } finally {
            sessao.close();
        }
        return produto;
    }

    public void excluir(Produto produto) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;

        try {
            transacao = sessao.beginTransaction();
            sessao.delete(produto);
            transacao.commit();
        } catch (RuntimeException ex) {
            if (transacao != null) {
                transacao.rollback();
            }
            throw ex;
        } finally {
            sessao.close();
        }
    }

    public void editar(Produto produto) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;
        try {
            transacao = sessao.beginTransaction();
            sessao.update(produto);
            transacao.commit();
        } catch (RuntimeException ex) {
            if (transacao != null) {
                transacao.rollback();
            }
            throw ex;
        } finally {
            sessao.close();
        }
    }

}

Domain Product

package domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table
@NamedQueries({ @NamedQuery(name = "Produto.listar", query = "SELECT produto FROM Produto produto"),
        @NamedQuery(name = "Produto.buscarPorCodigo", query = "SELECT produto FROM Produto produto WHERE produto.id = :id") })
public class Produto implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    private Long id;

    @Column(length = 50, nullable = false)
    private String nome;

    @Column(nullable = false)
    private Float valor;

    @Column(nullable = false)
    private Integer quantidade;

    @Lob
    private byte[] image;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "categoria_id", referencedColumnName = "id", nullable = false)
    private Categoria categoria;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Float getValor() {
        return valor;
    }

    public void setValor(Float valor) {
        this.valor = valor;
    }

    public Integer getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(Integer quantidade) {
        this.quantidade = quantidade;
    }

    public Categoria getCategoria() {
        return categoria;
    }

    public void setCategoria(Categoria categoria) {
        this.categoria = categoria;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public boolean hasimage() {
        return this.image != null && this.image.length > 0;
    }

    @Override
    public String toString() {
        return "Produto [id=" + id + ", nome=" + nome + ", valor=" + valor + ", quantidade=" + quantidade + ", image=" + image + ", categoria="
                + categoria + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Produto other = (Produto) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

}

web xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <!--Nome da Aplicação -->
    <display-name>Restaurante</display-name>

    <!--Arquivo Principal da aplicação -->
    <welcome-file-list>
        <welcome-file>pages/principal.xhtml</welcome-file>
    </welcome-file-list>

    <!-- Configuração do Servlet do JSF -->
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <!-- Tema do PrimeFaces -->
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>start</param-value>
    </context-param>

    <!-- Carregamento do Contexto do hibernate -->
    <listener>
        <listener-class>util.ContextListener</listener-class>
    </listener>

    <!-- Para salvar imagens -->
    <filter>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

</web-app>

Productocadastro.xhtml

<ui:define name="conteudo">
    <h:form id="frmProdutoCad" enctype="multipart/form-data">
        <p:toolbar>
            <f:facet name="left">
                <h:outputText value="Produtos" />
            </f:facet>
        </p:toolbar>

        <h:panelGrid id="pnlProdutosCadDados" columns="2">

            <p:outputLabel value="Nome:" />
            <p:inputText size="30" maxlength="50"
                value="#{produtoBean.produtoCadastro.nome}" />

            <p:outputLabel value="valor:" />
            <p:inputText size="30" maxlength="50"
                value="#{produtoBean.produtoCadastro.valor}" />

            <p:outputLabel value="quantidade:" />
            <p:inputText size="30" maxlength="50"
                value="#{produtoBean.produtoCadastro.quantidade}" />
            <p:outputLabel value="Foto" for="foto" />
            <p:fileUpload id="foto" value="#{produtoBean.fotoCarro}" />

            <p:outputLabel value="Categoria:" />
            <p:selectOneMenu value="#{produtoBean.produtoCadastro.categoria}"
                converter="categoriaConverter"
                disabled="#{produtoBean.acao == 'Excluir'}">
                <f:selectItem itemValue="" itemLabel="Selecione uma Categoria" />
                <f:selectItems value="#{produtoBean.listaCategoria}"
                    var="categoria" itemValue="#{categoria}"
                    itemLabel="#{categoria.nome}" />
                <f:validateBean />
            </p:selectOneMenu>

        </h:panelGrid>

        <h:panelGrid columns="5">
            <p:commandButton value="Novo" actionListener="#{produtoBean.novo}"
                update=":frmProdutoCad:pnlProdutosCadDados"
                rendered="#{produtoBean.acao == 'Novo'}" />
            <p:commandButton value="Salvar" ajax="false"
                actionListener="#{produtoBean.salvar}"
                update=":msgGlobal :frmProdutoCad:pnlProdutosCadDados"
                rendered="#{produtoBean.acao == 'Novo'}" />
            <p:commandButton value="Excluir"
                actionListener="#{produtoBean.excluir}" update=":msgGlobal"
                rendered="#{produtoBean.acao == 'Excluir'}" />
            <p:commandButton value="Editar"
                actionListener="#{produtoBean.editar}" update=":msgGlobal"
                rendered="#{produtoBean.acao == 'Editar'}" />
            <p:button value="Voltar"
                outcome="/pages/produtoPesquisa.xhtml?faces-redirect=true" />
        </h:panelGrid>

    </h:form>
</ui:define>

Productopesquisa.xhtml

<ui:define name="metadata">
    <f:metadata>
        <f:event listener="#{produtoBean.carregarPesquisa}"
            type="preRenderView" />
    </f:metadata>
</ui:define>

<ui:define name="conteudo">
    <h:form>
        <p:toolbar>
            <f:facet name="left">
                <h:outputText value="Produtos" />
            </f:facet>
        </p:toolbar>

        <p:dataTable emptyMessage="Nenhum registro encontrado."
            value="#{produtoBean.listaProdutos}"
            filteredValue="#{produtoBean.listaProdutosFiltrados}"
            paginator="true" rows="6" var="produto">
            <f:facet name="footer">
                <p:button value="Novo"
                    outcome="/pages/produtoCadastro.xhtml?faces-redirect=true">

                    <f:param name="produtoacao" value="Novo" />
                </p:button>
            </f:facet>
            <p:column headerText="Nome: " filterBy="#{produto.nome}"
                sortBy="#{produto.nome}">
                <h:outputText value="#{produto.nome}" />
            </p:column>
            <p:column headerText="Opções">

                <p:button value="Excluir"
                    outcome="/pages/produtoCadastro.xhtml?faces-redirect=true">
                    <f:param name="produtoacao" value="Excluir" />
                    <f:param name="produtocod" value="#{produto.id}" />
                </p:button>

                <p:button value="Editar"
                    outcome="/pages/produtoCadastro.xhtml?faces-redirect=true">
                    <f:param name="produtoacao" value="Editar" />
                    <f:param name="produtocod" value="#{produto.id}" />
                </p:button>
            </p:column>
        </p:dataTable>
    </h:form>

</ui:define>

  • I do not believe that it is a better approach to have to record the image in the database, because the image weighs a lot, there is not be that it is for a very specific purpose, most save only the path in the database and the image in the external folder.

  • I’m trying to record at the bank because it’s an academic project, and when I started developing it I had some doubts whether it would record at the bank or the image path, and thought it best to start trying to record in the bank first and in case of this many problems later I would try to record the image path, thank you very much for the @wladyband tip

1 answer

0


Take a look here Ucas.

    <p:fileUpload fileUploadListener="#{produtoBean.fotoCarro}"
                mode="advanced" dragDropSupport="false" sizeLimit="5000000"
                fileLimit="1" allowTypes="/(\.|\/)(pdf|jpe?g|png)$/" id="upload" />

Notice that fileUploadListener points to the attribute, which in your case would be fotoCarro, that in the file xhtml.

In the Managebean once I used it like this.

    public void handleFileUpload(FileUploadEvent event) {

    arquivo = new Arquivo();

    arquivo.setNome(event.getFile().getFileName());

    arquivo.setTipo(event.getFile().getContentType());

    arquivo.setConteudo(event.getFile().getContents());

    NotificarUsuario.mostrarMensagem(FacesMessage.SEVERITY_INFO, "Upload", event.getFile().getFileName()
            + " foi subido com sucesso.");

}

here I took the image that came in Event.

  • thanks a lot for the help I’ll try to put what you suggested.

Browser other questions tagged

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