FileUpload Primefaces

Bom dia pessoal,

Estou a 3 dias tentando fazer o upload automático do primefaces, pesquisei nos fóruns, mas nenhuma das alternativa e soluções me adiantaram, pois o upload não chamou o método do java. Atualmente os meu arquivos estão com a seguinte configuração e códigos:

web.xml ( Parte do código xml )


<filter>  
        <filter-name>PrimeFaces FileUpload Filter</filter-name>  
        <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>  
        <init-param>  
            <param-name>thresholdSize</param-name>  
            <param-value>51200</param-value>  
        </init-param>  
        <init-param>  
            <param-name>uploadDirectory</param-name>  
            <param-value>C:\temp</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>PrimeFaces FileUpload Filter</filter-name>  
        <servlet-name>Faces Servlet</servlet-name>  
    </filter-mapping>  
      <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification     2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
 <filter>

FileUploadController.java

import java.io.Serializable;
import java.util.logging.Logger;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.primefaces.event.FileUploadEvent;

@ManagedBean(name="fileUploadController")
@RequestScoped
public class FileUploadController implements Serializable{

	private static final long serialVersionUID = 1L;
	private static final int BUFFER_SIZE = 6124;

	  private Logger logger = Logger.getLogger(FileUploadController.class.getName());  
	  
    /** Creates a new instance of UploadBean */
    public FileUploadController() {
    
    }

    public void handleFileUpload(FileUploadEvent event){
    	
    	System.out.println("Deu certo");
    }    
    
}

Codigo.xhtml

<ui:composition 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>
	</h:head>

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

				<p:fileUpload
					fileUploadListener="{fileUploadController.handleFileUpload}"
					mode="advanced" update="messages" sizeLimit="100000"
					allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />

				<p:growl id="messages" showDetail="true" />

			</h:form>
	
	</h:body>
</ui:composition>

Tentou mudar o scope do seu MB para session?

Já sim cara. Mas não deu nenhum efeito.

Mas valeu a resposta.

não ta faltando um

auto="true"

na tag

&lt;p:fileUpload

???

att,

Não não.

Esse auto = " true" significa que o upload vai ser automatico, ou seja, quando eu selecionar o arquivo ele ja vai enviar o arquivo para upload, sem precisar clicar em outro botão para agir.

[quote=Thyago!]Não não.

Esse auto = " true" significa que o upload vai ser automatico, ou seja, quando eu selecionar o arquivo ele ja vai enviar o arquivo para upload, sem precisar clicar em outro botão para agir.[/quote]

e não é isso oque vc quer?

Cara, eu coloquei ali o upload automatico, mas leia a pergunta inteira. Ela diz no final ali que NAOR ESTA CHAMANDO O METODO JAVA, é isso que eu quero resolver.

O meu funcionou da seguinte forma:

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> </filter-mapping>

Utilizo GlassFish, no glassfish-web.xml adicionei o código abaixo:

<parameter-encoding default-charset="UTF-8"/>

Meu Bean

[code]import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.UploadedFile;

@ManagedBean
@ViewScoped
public class FileUploadBean {

private UploadedFile file;

public UploadedFile getFile() {
    return file;
}

public void setFile(UploadedFile file) {
    this.file = file;
}

public void upload() {
    FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
	FacesContext.getCurrentInstance().addMessage(null, msg);
}

}[/code]

Minha Página provisória

[code]<?xml version='1.0' encoding='UTF-8' ?>

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

        <p:messages showDetail="true"/>

        <p:fileUpload value="#{fileUploadBean.file}" 
                      mode="simple"/>

        <p:commandButton value="Importar" ajax="false"
                    actionListener="#{fileUploadBean.upload}"/>

    </h:form>

</body> 
[/code]

Adicionei as Lib’s
commons-fileupload-1.2.2.jar
commons-io-2.1.jar

JSF 2.0
Primefaces: primefaces-3.0.1.jar

Espero ter ajudado!

Podem ser as Libs. Eu estava com um problema com o Fileupload do Rich e o problema eram as libs principalmente os Commons.
Flw

Noite Galera

Então Thyago não sei se te ajuda, mas vamos lá.
Estou usando Glassfish 3.1, Primefaces 2.2.1 e EJB 3, estou passando a configuração as vezes pode não bater como e com o que está desenvolvendo.

XHTML

&lt;h:form id="UpImagem" enctype="multipart/form-data"&gt;
                    &lt;p:messages showDetail="true"/&gt;  
                    &lt;p:fileUpload label="Selecionar..." sizeLimit="9999999"  fileUploadListener="#{AnexoMB.fileUploadAction}" auto="true" allowTypes="*.jpg;,*.txt;,*.doc;,*.pdf;,*.gif;" multiple="false"/&gt;
&lt;/h:form&gt;

WEB.XML

&lt;filter-name&gt;PrimeFaces FileUpload Filter&lt;/filter-name&gt;
    &lt;filter-class&gt;org.primefaces.webapp.filter.FileUploadFilter&lt;/filter-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;uploadDirectory&lt;/param-name&gt;
        &lt;param-value&gt;C:/arquivo/imagem/&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;thresholdSize&lt;/param-name&gt;
        &lt;param-value&gt;10000&lt;/param-value&gt;
    &lt;/init-param&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
    &lt;filter-name&gt;PrimeFaces FileUpload Filter&lt;/filter-name&gt;
    &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
  &lt;/filter-mapping&gt;

É estranho pq só com isso já ta salvando, mas não ta salvando como eu quero, ele cria uma arquivo TMP dentro da pasta “C:/arquivo/imagem/” e mesmo qualquer alteração que estou fazendo no ManagedBean não surge efeito, se tiver uma luz heheheh.
Mas abaixo segue a minha parte incomplete o qual nem sei se está funcionando ou não.

AnexoFachada

@Stateless
public class AnexoFachada {
    
    @EJB
    private AnexoDAO anexoDAO;
    private Anexo anexo;
    
    public void inserir(Anexo anexo) {
        anexoDAO.inserir(anexo);
    }
    
    public Anexo recuperarPorId(Integer id) {
        return anexoDAO.recuperarPorId(id);
    }

    public void inserir(byte[] img) {
        anexoDAO.inserir(anexo);
    }
}

AnexoDAO

@Stateless
public class AnexoDAO {

    @PersistenceContext
    private EntityManager em;

    public void inserir(Anexo anexo) {
        em.persist(anexo);
        em.merge(anexo);
        
    }

    public Anexo recuperarPorId(Integer id) {
        return em.find(Anexo.class, id);
    }
}

Anexo(bean)

@Entity
@Table(name = "anexo")
@NamedQueries({
    @NamedQuery(name = "Anexo.findAll", query = "SELECT a FROM Anexo a"),
    @NamedQuery(name = "Anexo.findByAnexoId", query = "SELECT a FROM Anexo a WHERE a.anexoId = :anexoId"),
    @NamedQuery(name = "Anexo.findByCaminho", query = "SELECT a FROM Anexo a WHERE a.caminho = :caminho"),
    @NamedQuery(name = "Anexo.findByNome", query = "SELECT a FROM Anexo a WHERE a.nome = :nome")})
public class Anexo implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "anexo_id", nullable = false)
    @SequenceGenerator(name="Anexo_Generator", sequenceName="anexo_sequence", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="Anexo_Generator")  
    private Integer anexoId;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "caminho", nullable = false, length = 255)
    private String caminho;
    @Size(max = 255)
    @Column(name = "nome", length = 255)
    private String nome;
    @Lob
    @Column(name = "arquivo")
    private byte[] arquivo;

    public Anexo() {
    }

    public Anexo(Integer anexoId) {
        this.anexoId = anexoId;
    }

    public Anexo(Integer anexoId, String caminho) {
        this.anexoId = anexoId;
        this.caminho = caminho;
    }

    public Integer getAnexoId() {
        return anexoId;
    }

    public void setAnexoId(Integer anexoId) {
        this.anexoId = anexoId;
    }

    public String getCaminho() {
        return caminho;
    }

    public void setCaminho(String caminho) {
        this.caminho = caminho;
    }

    public String getNome() {
        return nome;
    }

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

    public byte[] getArquivo() {
        return arquivo;
    }

    public void setArquivo(byte[] arquivo) {
        this.arquivo = arquivo;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (anexoId != null ? anexoId.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 Anexo)) {
            return false;
        }
        Anexo other = (Anexo) object;
        if ((this.anexoId == null && other.anexoId != null) || (this.anexoId != null && !this.anexoId.equals(other.anexoId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "negocio.entidade.Anexo[ anexoId=" + anexoId + " ]";
    }  
}

ManagedBean
Acredito que meu MB está errado, porque parece que não chama o método e não persiste no banco.

@ManagedBean(name = "anexoMB")
@SessionScoped
public class AnexoMB implements Serializable {
    
    private Anexo anexo;
    private ListDataModel anexos;
    private byte[]img;
    private StreamedContent file;
    
    
    @EJB
    private AnexoFachada anexoFachada;
    
    public void AnexoMB(){}

    public Anexo getAnexo() {
        return anexo;
    }

    public void setAnexo(Anexo anexo) {
        this.anexo = anexo;
    }
    
    public StreamedContent getFile() {return file;}
    public void setFile(StreamedContent file) {this.file = file;}
    
    public void recuperarAnexo() {
        this.anexo = (Anexo) this.anexos.getRowData();
    }
    
    public String montarPaginaParaInsercao() {
        this.anexo = new Anexo();
        return "/anexo/InserirAnexo";
    }
    
    
    public void fileUploadAction(FileUploadEvent e) throws IOException{
        Anexo img = null;
       
        try{
              UploadedFile arq = e.getFile();
              InputStream in = new BufferedInputStream(arq.getInputstream());
              String caminho = FacesContext.getCurrentInstance().getExternalContext().getRealPath("C:/arquivo/imagem/" + e.getFile().getFileName());
              File fileAnexo = new File(caminho);
              fileAnexo.getParentFile().mkdirs();
              FileOutputStream fout = new FileOutputStream(caminho);
            
            while (in.available() != 0) {
                fout.write(in.read());
            }
            
            fout.close();
            anexo = new Anexo();
            anexo.setCaminho(caminho);
            anexoFachada.inserir(img);
            
        } catch (Exception ex) {
            ex.getMessage();
            if (anexo != null) {
                new File(anexo.getCaminho()).delete();
            }
        }
    }
}

Opa,
cara eu tava com esse mesmo problema e resolvi da seguinte forma.

Estou usando o Glassfish, coloquei os .jar (common-io e common-fileupload) no diretorio lib do meu dominio (C:\glassfish3\glassfish\domains\domain1\lib).

Estava colocando estes “jars” na pasta lib do WEB-INF e mapeando o classpaph , mas não adiantava, na hr de publicar minha aplicação lançava uma excessão “… Caused by: java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory…” que é utilizada pela classe FileUploadFilter que está no web.xml.

No meu casoo funcionou.

Espero ter ajudado.

Abraço.

Boa noite,

Então eu consegui fazer o tal UP, salvando na pasta.
vlw galera pela ajuda.

[quote=alexandergtk]Boa noite,

Então eu consegui fazer o tal UP, salvando na pasta.
vlw galera pela ajuda.[/quote]

Boa noite!!
estou com o mesmo problema aqui, poderia dizer como fez pra resolver!!?..seu código postado anteriormente mudou muito??!
Obrigado!

Bean

package br.com.projeto.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import javax.faces.context.FacesContext;

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

import br.com.projeto.beans.Arquivos;
import br.com.projeto.dao.HibernateDao;

@SessionScoped
@ManagedBean
public class ArquivosBean implements Serializable {
	private static final long serialVersionUID = 1L;
	private Arquivos arquivo = new Arquivos();
	private List<Arquivos> arquivos = new ArrayList<Arquivos>();
	@SuppressWarnings("unused")
	private StreamedContent file;

	public String fileUploadAction(FileUploadEvent event) throws IOException {
		try {
			arquivo.setNome(event.getFile().getFileName());
			byte[] conteudo = event.getFile().getContents();
			String caminho = "C:\\arquivos\\" + event.getFile().getFileName();
			FileOutputStream fos = new FileOutputStream(caminho);
			fos.write(conteudo);
			fos.close();
			HibernateDao<Arquivos> hibernateDao = new HibernateDao<Arquivos>(Arquivos.class);
			arquivo.setCaminho(caminho);
			arquivo.setTamanho(conteudo.length);
			String nomeArquivo = arquivo.getNome();
			int e = nomeArquivo.lastIndexOf(".");
			arquivo.setTipo(nomeArquivo.substring(e));
			hibernateDao.salvar(arquivo);
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Arquivo Salvo!", arquivo.getNome()));
		} catch (Exception e) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", " " + e));
		} finally {
			arquivo = new Arquivos();
			arquivos = new ArrayList<Arquivos>();
			file = null;
		}
		return "Arquivos.xhtml";
	}

	public List<Arquivos> getListArquivos() {
		HibernateDao<Arquivos> hibernateDao = new HibernateDao<Arquivos>(Arquivos.class);
		arquivos = hibernateDao.getBeans();
		return arquivos;
	}

	public void remove() {
		try {
			HibernateDao<Arquivos> hibernateDao = new HibernateDao<Arquivos>(Arquivos.class);
			Integer id = arquivo.getId();
			arquivo = hibernateDao.getBean(id);
			new File(arquivo.getCaminho()).delete();
			hibernateDao.deletar(arquivo);
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Arquivo Deletado!", arquivo.getNome()));
		} catch (Exception e) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", " " + e));
		} finally {
			arquivo = new Arquivos();
			arquivos = new ArrayList<Arquivos>();
			file = null;
		}
	}

	public StreamedContent getFile() throws FileNotFoundException {
		HibernateDao<Arquivos> hibernateDao = new HibernateDao<Arquivos>(Arquivos.class);
		Integer id = arquivo.getId();
		arquivo = hibernateDao.getBean(id);
		String caminho = arquivo.getCaminho();
		FileInputStream stream = new FileInputStream(caminho);
		return file = new DefaultStreamedContent(stream, caminho, arquivo.getNome());
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public Arquivos getArquivo() {
		return arquivo;
	}

	public void setArquivo(Arquivos arquivo) {
		this.arquivo = arquivo;
	}

	public List<Arquivos> getArquivos() {
		return arquivos;
	}

	public void setArquivos(List<Arquivos> arquivos) {
		this.arquivos = arquivos;
	}
}

jsf

<?xml version="1.0" encoding="ISO-8859-1"?>
<!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.prime.com.tr/ui">
<h:head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<title>Arquivos</title>
</h:head>
<h:body>
	<h:form enctype="multipart/form-data" update=":form:display">
		<p:growl id="messages" />
		<div align="center">
			<p:panel header="Arquivos" style="width:1050px">
				<ui:include src="/paginas/Menu.xhtml" />


				<p:fileUpload fileUploadListener="#{arquivosBean.fileUploadAction}"
					update="display" multiple="true" />
				<br />
				´
				
				
				<p:dataTable var="arquivos" value="#{arquivosBean.listArquivos}"
					widgetVar="arquivosTable"
					emptyMessage="Nenhum arquivos Encontrado Nessas Condições"
					rowStyleClass="#{empty rowIx or rowIx
 mod 2 ne 0 ? 'even-row' : 'odd-row'}"
					rowIndexVar="rowIx" id="display" rows="30">

					<f:facet name="header">
						<p:outputPanel>
							<h:outputText value="Procurar em todos os campos:" />
							<p:inputText id="globalFilter" onkeyup="arquivosTable.filter()" />
						</p:outputPanel>
					</f:facet>

					<p:column filterBy="#{arquivos.id}" headerText="Código" footerText="Código"
						filterMatchMode="contains" style="width: 40px">
						<h:outputText value="#{arquivos.id}" style="width: 40px" />
					</p:column>

					<p:column filterBy="#{arquivos.nome}" headerText="Descrição"
						footerText="Descrição" filterMatchMode="contains">
						<h:outputText value="#{arquivos.nome}" />
					</p:column>

					<p:column filterBy="#{arquivos.tipo}" headerText="Tipo"
						footerText="Tipo" filterMatchMode="contains" style="width: 40px">
						<h:outputText value="#{arquivos.tipo}" style="width: 40px" />
					</p:column>

					<p:column filterBy="#{arquivos.tamanho}" headerText="Tamanho"
						footerText="Tamanho" filterMatchMode="contains"
						style="width: 140px">
						<h:outputText value="#{arquivos.tamanho}" style="width: 140px" />
					</p:column>



					<p:column style="width:100px">
						<h:panelGrid columns="2" styleClass="actions" cellpadding="2">

							<p:commandButton image="ui-icon-disk" title="Download"
								ajax="false">
								<f:setPropertyActionListener value="#{arquivos.id}"
									target="#{arquivosBean.arquivo.id}" />
								<p:fileDownload value="#{arquivosBean.file}" />
							</p:commandButton>

							<p:commandButton image="ui-icon-trash" title="Excluir"
							onclick="confirmation.show()">
							<f:setPropertyActionListener value="#{arquivos.id}"
									target="#{arquivosBean.arquivo.id}" />
						</p:commandButton>
						</h:panelGrid>
					</p:column>
				</p:dataTable>

<p:confirmDialog id="confirmDialog" message="Confirma Exclusão?"
			severity="alert" widgetVar="confirmation">

			<p:commandButton id="confirm" value="Sim" update="display, messages"
				oncomplete="confirmation.hide()"
				actionListener="#{arquivosBean.remove}">

			</p:commandButton>
			<p:commandButton id="decline" value="Não"
				onclick="confirmation.hide()" type="button" />
		</p:confirmDialog>

				<style>
.ui-datatable .ui-datatable-data .even-row td {
	background-color: #fcefa1;
	border-right: solid 0px #4e6769;
}

.ui-datatable .ui-datatable-data .odd-row td {
	background-color: #f7f7f7;
	border-right: solid 0px #4e6769;
}
</style>
			</p:panel>
		</div>
	</h:form>
</h:body>
</html>

bean


package br.com.projeto.beans;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Arquivos implements Serializable{

	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue
	private Integer id;
	private String nome;
	private String caminho;
	private String tipo;
	private float tamanho;

	public Integer getId() {
		return id;
	}

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

	public String getNome() {
		return nome;
	}

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

	public String getCaminho() {
		return caminho;
	}

	public void setCaminho(String caminho) {
		this.caminho = caminho;
	}

	public String getTipo() {
		return tipo;
	}

	public void setTipo(String tipo) {
		this.tipo = tipo;
	}

	public float getTamanho() {
		return tamanho;
	}

	public void setTamanho(float tamanho) {
		this.tamanho = tamanho;
	}

}