Upload de arquivos Jsf Primafaces

10 respostas
E

Pessoal,

Preciso fazer uma tela que estou desenvolvendo, upload de arquivo neste tela

Estou usando jsf e primafaces

e Vou fazer uma outra tela para ler esses arquivos

Alguem pode me dar alguma luz ???

Obrigado

10 Respostas

D

Dá uma olhado no showCase

http://www.primefaces.org/showcase/ui/fileUploadMultiple.jsf

E

Daniel, blz. …Upload…e como faço para ler esse arquivo que fez upload ?? Seria um download

D

o que exatamente você quer dizer com “ler”?

você deseja ler um .txt e procurar dados, você quer mostrar um .pdf ao usuário…

E

For example,

O usuario tem uma jpg ou um pdf ou arquivo zip e gostaria de anexar isso …upload.

e um determinado momento o usuario terá que vizualizar o que anexou …

Entendeu

D

Beleza.

Eu faria assim: gravaria o arquivo que ele anexou (upload) em uma pasta no servidor. E em uma tabela do banco de dados chamada “arquivos” eu guardaria o caminho, nome, data de anexo.

Na página de visualização de arquivos eu mostraria um p:dataTable com as informações da tabela arquivos, com uma opção para download.

E

Mas entao vc copiaria este arquivo no servidor???

D

É sim cara…

Quando o usuário fizer o upload do arquivo ele vai pra uma pasta do servidor, e pra o banco eu mando só o caminho onde está o arquivo. Entendeu?

M

Cara, eu tenho um post que fiz a um tempo atrás, vê se te ajuda neste link.

C

Evandro Araujo,

a algum tempo tive esse mesmo problema em um projeto meu, onde o usuario precisava fazer um upload de uma imagem (de uma redação) e depois, precisava mostrar a redação carregada ao professor.

Meu código eh esse:

No RedacaoMB tem os metodos onde a imagem é inserida

package beans;

import auxiliar.FacesUtil;
import dao.AlunoJpaController;
import dao.RedacaoJpaController;
import dao.exceptions.NonexistentEntityException;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import modelo.Redacao;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

/**
 * @author Monnalisa Christina ManagedBean do Aluno - projeto Corresys versão
 * 1.0 data:30/05/2013 Inserção de imagem funcionando
 */
@ManagedBean
@SessionScoped
public class RedacaoMB implements Serializable {

    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("CORRESYS_1.0PU");
    RedacaoJpaController dao = new RedacaoJpaController(emf);
    private String mensagem = "";
    private List<Redacao> redacoes = new ArrayList<Redacao>();
    private Redacao redacao = new Redacao();
    private UploadedFile foto;
    private DefaultStreamedContent graphicText;
  
    
    public RedacaoMB() {
        pesquisar();
    }

    public String getMensagem() {
        return mensagem;
    }

    public void setMensagem(String mensagem) {
        this.mensagem = mensagem;
    }

    public Redacao getRedacao() {
        return redacao;
    }

    public void setRedacao(Redacao redacao) {
        this.redacao = redacao;
    }

    public List<Redacao> getRedList() {
        return redacoes;
    }
    
     //pesquisar todas redacoes
    public int pesquisar() {
        redacoes = dao.findRedacaoEntities();
        return redacoes.size();

    }

    /**
     * @return the imagem
     */
    public UploadedFile getFoto() {
        return foto;
    }

    /**
     * @param imagem the imagem to set
     */
    public void setFoto(UploadedFile foto) {
        this.foto = foto;
    }
    
    //pesquisar todas redacoes
    public int pesquisar() {
        redacoes = dao.findRedacaoEntities();
        return redacoes.size();

    }


    /**
     * método chamado para fazer upload da imagem e salvar todos os dados no BD.
     */
    public void upload() {
        if (getFoto() != null) {

            byte[] imgNova = foto.getContents();

            redacao.setImagem(imgNova);

            try {
                dao.create(redacao);
                this.setMensagem(this.redacao.getTitulo() + " cadastrado(a) com sucesso ! ");
                redacao = new Redacao();
            } catch (Exception ex) {
                setMensagem(this.redacao.getTitulo() + " já existe no sistema, ou matrícula do Aluno e Corretor são incorretas, cadastro não realizado!");
                Logger.getLogger(AlunoMB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        pesquisar();
    }

    public void excluir() {
        try {
            dao.destroy(redacao.getId());
            setMensagemExclusao(this.redacao.getTitulo() + "  foi excluído(a) com sucesso!");
            redacao = new Redacao();
        } catch (NonexistentEntityException ex) {
            this.setMensagemExclusao("id não existe");
            Logger.getLogger(RedacaoMB.class.getName()).log(Level.SEVERE, null, ex);
        }
        pesquisar();
    }

    public void alterar() throws Exception {

        if (getFoto() != null) {

            byte[] imgNova = foto.getContents();

            redacao.setImagem(imgNova);

            try {
                dao.edit(redacao);
                setMensagemAlteracao(this.redacao.getTitulo() + " foi alterado(a) com sucesso!");
                redacao = new Redacao();
            } catch (NonexistentEntityException ex) {
                this.setMensagemAlteracao("id não existe");
                Logger.getLogger(RedacaoMB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        pesquisar();
    }

    /**
     * Esse método é usado pra fazer a imagem ser exibida na tela.
     */
    public StreamedContent getFotoStreamed() {

        if (redacao.getImagem() == null) {
            BufferedImage bufferedImg = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bufferedImg.createGraphics();
            g2.drawString("This is a text", 0, 10);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                ImageIO.write(bufferedImg, "png", os);
            } catch (IOException ex) {
                Logger.getLogger(RedacaoMB.class.getName()).log(Level.SEVERE, null, ex);
            }
            graphicText = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");

            return graphicText;
        }
        //retorna a imagem gravada no BD
        return new DefaultStreamedContent(new ByteArrayInputStream(redacao.getImagem()));
    }

    
}

neste código aki vc só deve levar em conta a variavel PRIVATE BYTE[] IMAGEM, q serve pra guardar a imagem

package modelo;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;

/**
 * @author Monnalisa Christina
 * Classe redação - projeto Corresys versão 1.0
 * data:15/05/2013
 */

@Entity
public class Redacao implements Serializable {
    
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String tema;
    private String titulo;
    private float nota = (float) 0.0;//Nota geral da redação
    private String status;
    private String matriculaCorretor;
    private String matriculaAluno;
    private byte[] imagem;


    
     @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Redacao)) {
            return false;
        }
        Redacao other = (Redacao) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "modelo.Redacao[ id=" + id + " ]";
    }
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    
     /**
     * @return the tema
     */
    public String getTema() {
        return tema;
    }

    /**
     * @param tema the tema to set
     */
    public void setTema(String tema) {
        this.tema = tema;
    }

    /**
     * @return the titulo
     */
    public String getTitulo() {
        return titulo;
    }

    /**
     * @param titulo the titulo to set
     */
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    /**
     * @return the nota
     */
    public float getNota() {
        return nota;
    }

    /**
     * @param nota the nota to set
     */
    public void setNota(float nota) {
        this.nota = nota;
    }

    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }
   
    /**
     * @return the imagem
     */
    public byte[] getImagem() {
        return imagem;
    }

    /**
     * @param imagem the imagem to set
     */
    public void setImagem(byte[] imagem) {
        this.imagem = imagem;
    }

    
    /**
     * @return the matriculaCorretor
     */
    public String getMatriculaCorretor() {
        return matriculaCorretor;
    }

    /**
     * @param matriculaCorretor the matriculaCorretor to set
     */
    public void setMatriculaCorretor(String matriculaCorretor) {
        this.matriculaCorretor = matriculaCorretor;
    }

    /**
     * @return the matriculaAluno
     */
    public String getMatriculaAluno() {
        return matriculaAluno;
    }

    /**
     * @param matriculaAluno the matriculaAluno to set
     */
    public void setMatriculaAluno(String matriculaAluno) {
        this.matriculaAluno = matriculaAluno;
    }

}

aki esta o html para fazer o upload

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">

    <h:head>

        <f:facet name="first">
            <meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
            <title>Cadastro_redacao</title>
        </f:facet>

    </h:head>

    <h:body>

        <h:form>  

                   ...

        </h:form> 

        <br/>

        <p:layoutUnit position="center" size="100" resizable="true" closable="true" collapsible="true">

            <center>
                <br/>
                <h:outputText style="color:red" value="#{redacaoMB.mensagem}"/>
            </center>
            <p:growl/>
            <h:form id="formRed" enctype="multipart/form-data">

                <h:inputHidden  value="#{redacaoMB.redacao.id}"/>
                <br/>
                <p:panel header="CADASTRO DE REDAÇÃO">
    
                    <br/>
                    Tema : * <p:inputText  size="100" value="#{redacaoMB.redacao.tema}" required="true" requiredMessage="Tema obrigatória" maxlength="250" ></p:inputText><h:message for="tema"  style="color:red"/>
                    <br/>
                    <br/>
                    Título : * <p:inputText size="100" value="#{redacaoMB.redacao.titulo}" required="true" requiredMessage="Campo título não foi preenchido" maxlength="250"></p:inputText><h:message for="nome" style="color:red"/>
                    <br/>
                    <br/>
                    Matrícula Aluno : * <p:inputMask title="Matrícula" value="#{redacaoMB.redacao.matriculaAluno}" required="true" requiredMessage="Matrícula obrigatória" maxlength="10" mask="[telefone removido]"></p:inputMask><h:message for="matrícula"  style="color:red"/>
                    <br/>
                    <br/>
                    Matrícula Corretor : * <p:inputMask title="Matrícula" value="#{redacaoMB.redacao.matriculaCorretor}" required="true" requiredMessage="Matrícula obrigatória" maxlength="10" mask="[telefone removido]"></p:inputMask><h:message for="matrícula"  style="color:red"/>
                    <br/>
                    <br/>
                    Status : *
                    <p:selectOneMenu value="#{redacaoMB.redacao.status}" required="true" requiredMessage="Status obrigatório">    

                        <f:selectItem itemLabel="Corrigida" itemValue="Corrigida" />  
                        <f:selectItem itemLabel="Recorrigida" itemValue="Recorrigida"/>
                        <f:selectItem itemLabel="Não Corrigida" itemValue=" Nao Corrigida"/>

                    </p:selectOneMenu>
                    <br/>
                    <br/>
                    Data : * <p:calendar value="#{redacaoMB.redacao.dat}" timeZone="GMT-3" navigator="true" pattern="dd/MM/yyyy" size="10"/>
                    <br/>
                    <br/>
                    Redação : * <p:fileUpload mode="simple" value="#{redacaoMB.foto}" sizeLimit="[telefone removido]" allowTypes="/(\.|\/)(jpe?g)$/"/>  />
                    <br/>
                    <br/>
                    <hr/>
                    <h:commandButton value="Inserir" action="#{redacaoMB.upload()}" /><h:message for="nome" style="color:red"/>
                    <p:spacer height="22"/>
                    <h:commandButton value="Cancelar" action="administrador.xhtml"/>
                    <br/>
                    <br/>
                    <h:messages for="formRed" style="color:red"/>
                </p:panel>

            </h:form>

        </p:layoutUnit>

    </h:body>
</html>
e esse eh o html onde exibo a imagem
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui">


    <f:view contentType="text/html">
        <h:head>

            <f:facet name="first">
                <meta content='text/html; charset=UTF-8' http-equiv="Content-Type"/>
                <title>Corrigir_Redacao</title>
            </f:facet>

        </h:head>

        <h:body>
           
                 ...

            <br/>

            <p:fieldset legend="LISTA DE REDAÇÕES" style="color: cornflowerblue">
                <p:dataTable  id="tabelaReda" value="#{loginCorretorMB.redCorretor}" var="con" rendered="#{loginCorretorMB.pesquisar()> 0}" paginator="true" rows="10"  
                              paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}">

                    <p:column  >
                        <f:facet name="header">
                            <h:outputText value="Tema" style="color: white"/>
                        </f:facet>             
                        <h:form >
                            <h:commandLink value="${con.tema}">   
                                <f:setPropertyActionListener value="#{con}" target="#{redacaoMB.redacao}"/>
                            </h:commandLink>  
                        </h:form>
                    </p:column>

                    <p:column  >
                        <f:facet name="header">
                            <h:outputText value="Título" style="color: white"/>
                        </f:facet>             
                        <h:form >
                            <h:commandLink value="${con.titulo}">   
                                <f:setPropertyActionListener value="#{con}" target="#{redacaoMB.redacao}"/>
                            </h:commandLink>  
                        </h:form>
                    </p:column>


                    <p:column  >
                        <f:facet name="header">
                            <h:outputText value="Código da redação" style="color: white"/>
                        </f:facet>             
                        <h:form >
                            <h:commandLink value="${con.id}">   
                                <f:setPropertyActionListener value="#{con}" target="#{redacaoMB.redacao}"/>
                            </h:commandLink>  
                        </h:form>
                    </p:column>

                    <p:column>
                        <f:facet name="header">
                            <h:outputText value="Matricula Corretor" style="color: white"/>                   
                        </f:facet>
                        <h:form >
                            <h:commandLink action="#{redacaoMB.carregar(con.id)}">
                                <h:outputText value="${con.matriculaCorretor}"/>
                            </h:commandLink>                        
                        </h:form>

                    </p:column>

                    <p:column>
                        <f:facet name="header">
                            <h:outputText value="Status" style="color: white"/>                   
                        </f:facet>
                        <h:form>
                            <h:commandLink action="#{redacaoMB.carregar(con.id)}">
                                <h:outputText  value="${con.status}"/>
                            </h:commandLink>                        
                        </h:form>
                    </p:column>

                </p:dataTable>  

            </p:fieldset>


            <h:form>
                <br/>
                <p:layoutUnit position="center" size="100" resizable="true" closable="true" collapsible="true">

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

                        <h:inputHidden  value="#{redacaoMB.redacao.id}"/>

                        <p:panel header="REDAÇÃO">
                            <br/>
                            <center>
                                <p:graphicImage value="#{redacaoMB.fotoStreamed}" width="700" height="800"/>
                            </center>  

                        </p:panel>
                        <br/>

                </p:layoutUnit>

            </h:form>

            <br/>

        </h:body>

    </f:view>
</html>

e o mais importante é que vc deve colar isso no seu web.xml

<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>  
        <url-pattern>*.jsf</url-pattern> 
    </filter-mapping>

e baixar as bibliotecas commons-io-2.4
e commons-fileupload-1.3

eu usei o Postgre como banco de dados para amazenar as iamgem

M

ChristinaMed,

Na classe redação senti falta deste parametro:

@Lob 
    @Basic(fetch = FetchType.EAGER)
    @Column(name="imagem")
     private byte[] imagem;

Também sentir falta do filtro para o tamanho da imagem:

<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
        <init-param>
            <param-name>thresholdSize</param-name>
            <param-value>51200</param-value>//tamanho em kb.
        </init-param>

e na busca do documento você pode fazer da seguinte forma:

public byte[] fileRecord(int iDdocumento){
       String hql = "SELECT d.arquivo FROM Documentos d WHERE d.codDocument= :id";
       Query consulta = HibernateUtil.getSession().createQuery(hql);
       consulta.setInteger("id", iDdocumento);
       return (byte[]) consulta.uniqueResult();
   }

Espero ter ajudado.

Criado 16 de maio de 2013
Ultima resposta 11 de jul. de 2013
Respostas 10
Participantes 4