Noite amigos,
Espero que te ajude nesse caso o meu está funcionando, sofri um pouco mas um amigo me ajudou solucionar a questão de gerar apenas uma arquivo temporario e quando fechava a aplicação ele sumia, segue.
Utilizei
Primefaces 2.2.1
Glassfish
EJB 3
*Obs. não esquecer de add dois jar
commons-fileupload.jar (estou usando a versão 1.2.2)
commons-io (estou usando a versão 2.1)
XHTML
<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<body>
<ui:define name="script">
<style type="text/css">
div#tudo {width: 800px;}
</style>
</ui:define>
<ui:define name="content">
<p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/>
<h:form>
<p:fileUpload fileUploadListener="#{anexoMB.fileUploadAction}" label="Selecionar..." update="messages" sizeLimit="9999999"
allowTypes="/(\.|\/)(gif|jpe?g|png|txt|pdf|doc)$/" multiple="false" auto="true" />
<p:messages id="messages" showDetail="true"/>
</h:form>
</ui:define>
</ui:composition>
</body>
</html>
ManagedBean
package apresentacao.managedbean;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.ListDataModel;
import negocio.entidade.Anexo;
import negocio.fachada.AnexoFachada;
import org.apache.commons.io.FilenameUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
@ManagedBean(name = "anexoMB")
@SessionScoped
public class AnexoMB{
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 {
try{
UploadedFile arq = e.getFile();
InputStream in = new BufferedInputStream(arq.getInputstream());
//File file = new File("c:/arquivo/imagem/ + arq.getInputstream());
File file = new File("c:/arquivo/imagem/" + arq.getFileName());
//File file = new File("c:/arquivo/imagem/teste/" + arq.getInputstream());
FileOutputStream fout = new FileOutputStream(file);
while (in.available() != 0) {
fout.write(in.read());
}
fout.close();
FacesMessage msg = new FacesMessage("O Arquivo ", file.getName() + " salvo.");
FacesContext.getCurrentInstance().addMessage("msgUpdate", msg);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
Classe (Entidade)
package negocio.entidade;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@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) {
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 + " ]";
}
}
Fachada
package negocio.fachada;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import negocio.entidade.Anexo;
import persistencia.AnexoDAO;
@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);
}
}
Persistencia
package persistencia;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import negocio.entidade.Anexo;
@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);
}
}
Adicinei esse trecho no meu
Web.xml
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>C:/arquivo/imagem</param-value>
</init-param>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>10000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>