Fórum upload com primefaces #419232
02/07/2012
0
Jose Boas
Curtir tópico
+ 0Posts
03/07/2012
Davi Costa
atenção que exige configuração no web.xml
vc precisa add esse filtro (esse trecho é para versão do primefaces 3.2, caso não dê certo para vc pesquisa p sua versão):
<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>102400000</param-value>
</init-param>
<!-- <init-param>
<param-name>uploadDirectory</param-name>
<param-value>/tmp</param-value>
</init-param> -->
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
att Davi
Gostei + 0
03/07/2012
Jose Boas
ManegedBean onde tem o método.
package ssoaso.web;
import java.io.*;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
@ManagedBean(name=arquivosBean)
@RequestScoped
public class ArquivosBean {
public void processFileUpload(FileUploadEvent event) throws IOException {
try{
FacesContext context = FacesContext.getCurrentInstance();
String caminho = context.getExternalContext().getRealPath(pessoa);
System.out.println(Caminho IMG = + caminho);
//Cria um arquivo UploadFile, para receber o arquivo do evento
UploadedFile arq = event.getFile();
InputStream in = new BufferedInputStream(arq.getInputstream());
//copiar para pasta do projeto
System.out.println(Arquivo = + arq.getFileName());
File file = new File(caminho + arq.getFileName());
//O método file.getAbsolutePath() fornece o caminho do arquivo criado
//Pode ser usado para ligar algum objeto do banco ao arquivo enviado
caminho = file.getAbsolutePath();
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();
}
}
}
<p:fileUpload fileUploadListener=#{arquivosBean.processFileUpload}
mode=advanced
update=messages
auto=true
label=Procurar
sizeLimit=9999999
allowTypes=/(\.|\/)(gif|jpe?g|png)$//>
<p:growl id=messages showDetail=true/>
Eu vejo executando o prime faces mas o metodo não, inclusive estes System.out.println é para ver se passou.
Gostei + 0
03/07/2012
Davi Costa
Configurou o web.xml?
att Davi
Gostei + 0
03/07/2012
Jose Boas
Gostei + 0
03/07/2012
Davi Costa
pois sem configuração nenhuma n vai funcionar.
lembroque na primeira vez que fiz, coloquei a configuração do web.xml, depois faltou algum jar.. tipo commons alguma coisa senão me engano mas deu o erro de falta de jar...
seria legal p comunidade te ajudar se vc mostrar suas configurações
Seu componente de upload precisa estar num form do jsf ou do primefaces
att Davi
Gostei + 0
03/07/2012
Jose Boas
<?xml version=1.0 encoding=UTF-8?>
<web-app xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns=http://java.sun.com/xml/ns/javaee xmlns:web=http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd xsi:schemaLocation=http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd id=WebApp_ID version=2.5>
<display-name>SsoWeb</display-name>
<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>102400000</param-value>
</init-param>
<!-- <init-param>
<param-name>uploadDirectory</param-name>
<param-value>/tmp</param-value>
</init-param> -->
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<!-- Tema do PrimeFaces -->
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>south-street</param-value>
</context-param>
<!-- Spring Security -->
<resource-ref>
<description>DataSource ConexaoDB</description>
<res-ref-name>jdbc/ConexaoDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Java Server Faces -->
<servlet>
<display-name>FacesServlet</display-name>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<!-- Filtro para interceptar para trabalhar Open Session in View -->
<filter>
<filter-name>conexaoFilter</filter-name>
<filter-class>ssoaso.web.filter.ConexaoHibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>conexaoFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
<!-- Use Documents Saved as *.xhtml -->
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
form onde chamo
<ui:composition>
<h:form id=edicaoPessoa>
<h:messages/>
<h:inputHidden value=#{pessoaBean.selecionada.idPessoa}/>
<h:panelGrid id=linha1 columns=5>
<h:outputLabel value=Nome for=nome/>
<h:outputLabel value=CTPS for=ctps/>
<h:outputLabel value=Série for=serie/>
<h:outputLabel value=UF for=ctpsEstado/>
<h:outputLabel value=RG for=rg/>
<p:inputText id=nome value=#{pessoaBean.selecionada.nome} size=38 maxlength=48 required=true/>
<p:inputText id=ctps value=#{pessoaBean.ctps} size=4 maxlength=7 required=true/>
<p:inputText id=serie value=#{pessoaBean.serie} size=2 maxlength=5 required=true/>
<p:selectOneMenu required=true id=ctpsEstado value=#{pessoaBean.ctpsEstado}>
<f:selectItem itemLabel=UF itemValue=/>
<f:selectItem itemLabel=Acre itemValue=AC/>
<f:selectItem itemLabel=Alagoas itemValue=AL/>
<f:selectItem itemLabel=Amazonas itemValue=AM/>
<f:selectItem itemLabel=Amapá itemValue=AP/>
<f:selectItem itemLabel=Bahia itemValue=BA/>
<f:selectItem itemLabel=Ceará itemValue=CE/>
<f:selectItem itemLabel=Distrito Federal itemValue=DF/>
<f:selectItem itemLabel=Espírito Santo itemValue=ES/>
<f:selectItem itemLabel=Goiás itemValue=GO/>
<f:selectItem itemLabel=Maranhão itemValue=MA/>
<f:selectItem itemLabel=Minas Gerais itemValue=MG/>
<f:selectItem itemLabel=Mato Grosso do Sul itemValue=MS/>
<f:selectItem itemLabel=Mato Grosso itemValue=MT/>
<f:selectItem itemLabel=Pará itemValue=PA/>
<f:selectItem itemLabel=Paraíba itemValue=PB/>
<f:selectItem itemLabel=Paraná itemValue=PR/>
<f:selectItem itemLabel=Pernambuco itemValue=PE/>
<f:selectItem itemLabel=Piauí itemValue=PI/>
<f:selectItem itemLabel=Rio de Janeiro itemValue=RJ/>
<f:selectItem itemLabel=Rio Grande do Norte itemValue=RN/>
<f:selectItem itemLabel=Rio Grande do Sul itemValue=RS/>
<f:selectItem itemLabel=Rondônia itemValue=RO/>
<f:selectItem itemLabel=Roraima itemValue=RR/>
<f:selectItem itemLabel=Santa Catarina itemValue=SC/>
<f:selectItem itemLabel=Sergipe itemValue=SE/>
<f:selectItem itemLabel=São Paulo itemValue=SP/>
<f:selectItem itemLabel=Tocantins itemValue=TO/>
</p:selectOneMenu>
<p:inputText id=rg value=#{pessoaBean.selecionada.rg} size=7 required=true maxlength=11/>
</h:panelGrid>
<h:panelGrid id=linha2 columns=4>
<h:outputLabel value=CPF for=cpf/>
<h:outputLabel value=PIS/PASEP for=pis/>
<h:outputLabel value=Endereço for=endereco/>
<h:outputText/>
<p:inputMask id=cpf value=#{pessoaBean.selecionada.cpf} required=true size=9 mask=999.999.999-99/>
<p:inputText id=pis value=#{pessoaBean.selecionada.pis} required=true size=7 maxlength=11/>
<p:inputText id=endereco value=#{pessoaBean.selecionada.endereco} required=true size=49 maxlength=50/>
<p:fileUpload fileUploadListener=#{pessoaBean.processFileUpload}
mode=advanced
update=messages
auto=true
label=Procurar
sizeLimit=9999999
allowTypes=/(\.|\/)(gif|jpe?g|png)$//>
<p:growl id=messages showDetail=true/>
</h:panelGrid>
</h:form>
</ui:composition>
tentei fazer com <p:fileUpload fileUploadListener=#{pessoaBean.processFileUpload}
e com <p:fileUpload fileUploadListener=#{arquivosBean.processFileUpload}
e nada. A pessoa é um managedBean do tipo viewscoped e o arquivo request
Gostei + 0
03/07/2012
Jose Boas
aciona
<p:messages showDetail=true/>
<p:fileUpload value=#{arquivosBean.file} mode=simple/>
<p:commandButton value=Submit ajax=false
actionListener=#{arquivosBean.upload} update=:linha2/>
tem alguma coisa a ver pelo fato de estar usando scope ve visão não no arquivoBean mas no pessoaBean tabView.
Isso me intriga.Mas eu quria não usar o simple.
Att
José Luiz Vilas Boas.
Gostei + 0
04/07/2012
Jose Boas
Gostei + 0
04/07/2012
Jose Boas
Gostei + 0
04/07/2012
Davi Costa
<?xml version=1.0 encoding=UTF-8 ?>
<ui:composition xmlns=http://www.w3.org/1999/xhtml
xmlns:f=http://java.sun.com/jsf/core
xmlns:h=http://java.sun.com/jsf/html
xmlns:c=http://java.sun.com/jsp/jstl/core
xmlns:ui=http://java.sun.com/jsf/facelets
xmlns:t=http://myfaces.apache.org/tomahawk
xmlns:p=http://primefaces.org/ui
template=/pages/template/template_padrao.xhtml>
<ui:define name=conteudo>
<div id=container align=left>
<img src=../../img/include.png />
<h1></h1>
<h:form enctype=multipart/form-data>
<t:saveState value=#{incluirDocumentoBean.documento}></t:saveState>
<h:outputLabel value=Contrato for=contrato />
<h:inputText id=contrato
value=#{incluirDocumentoBean.documento.codContrato}
label=Nome
required=true />
<h:outputLabel value=Matrícula for=matricula />
<h:inputText id=matricula
value=#{incluirDocumentoBean.documento.matricula}
label=Matrícula
required=true>
</h:inputText>
<p:fileUpload label=Procurar... cancelLabel=Cancelado mode=advanced
fileUploadListener=#{incluirDocumentoBean.fileUpload}
multiple=true sizeLimit=102400000 allowTypes=/(\.|\/)(gif|jpe?g|png|pdf|xls?x|odt|doc?x|dat|ods|txt|csv|lis)$/ />
<p:growl id=messages showDetail=true/>
<div align=right>
<h:commandLink value=Voltar
immediate=true
action=lista?faces-redirect=true />
<h:commandButton value=Salvar
action=#{incluirDocumentoBean.salvar}>
</h:commandButton>
</div>
</h:form>
</div>
</ui:define>
</ui:composition>
No bean
@Component(value=incluirDocumentoBean)
@Scope(value = request)
public class IncluirDocumentoBean extends BackingBean{
@Autowired
private DocumentoService documentoService;
@Autowired
private ArquivoService arquivoService;
private Documento documento;
public IncluirDocumentoBean() {
limparCampos();
}
private void limparCampos() {
documento = new Documento();
}
public void fileUpload(FileUploadEvent event) throws IOException {
String name = LINUX_REFERENCE
+ event.getFile().getFileName();
File file = new File(name);
documento.setIs(event.getFile().getInputstream());
documento.setOut(new FileOutputStream(file));
if(documento.getArquivos() == null){
documento.setArquivos(new ArrayList<Arquivo>());
}
Arquivo arquivo = new Arquivo();
arquivo.setNomeArquivo(name);
arquivo.setDocumento(documento);
arquivo.setUsuario(getUsuarioLogado());
documento.getArquivos().add(arquivo);
documento.setArquivo(name);
addMessage(FacesMessage.SEVERITY_INFO, Arquivo carregado com sucesso);
}
public String salvar(){
if(documento.getArquivos() != null && documento.getArquivos().size()>0){
try{
byte buf[] = new byte[1024];
int len;
while ((len = documento.getIs().read(buf)) > 0)
documento.getOut().write(buf, 0, len);
documento.getIs().close();
documento.getOut().close();
documentoService.insert(documento);
for (Arquivo arq : documento.getArquivos()) {
arquivoService.insert(arq);
}
addMessage(FacesMessage.SEVERITY_INFO, MSG_OPERACAO_CONCLUIDA);
limparCampos();
}catch (DataIntegrityViolationException e) {
addMessage(FacesMessage.SEVERITY_ERROR, Documento já cadastrado para mesma matrícula e contrato.);
return null;
}
catch (Exception e) {
addMessage(FacesMessage.SEVERITY_ERROR, Falha no carregamento do Arquivo.);
return null;
}
}else{
addMessage(FacesMessage.SEVERITY_WARN, Arquivo é obrigatório.);
}
return null;
}
att Davi
Gostei + 0
04/07/2012
Jose Boas
Obrigado.
Gostei + 0
04/07/2012
Jose Boas
Gostei + 0
05/07/2012
Davi Costa
att Davi
Gostei + 0
05/07/2012
Jose Boas
Gostei + 0
05/07/2012
Davi Costa
n sei de cabeça de onde baixar..pesquisa...
vou te passar a versão q eu uso: tomahawk20-1.1.11.jar
att Davi
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)