Upload nÃo funciona!

16 respostas
C

To tentando trabalhar com o rch:upload, porém nem entra no método do upload!!!

Segue meu .xhtml

.
.
.
<h:panelGrid columns="2" columnClasses="top,top">
			
			<rich:fileUpload fileUploadListener="#{upload.upload}"
				maxFilesQuantity="5" addControlLabel="Adicionar"
				clearAllControlLabel="Limpar tudo" clearControlLabel="limpar"
				stopEntryControlLabel="Parar" uploadControlLabel="Enviar"
				doneLabel="Arquivo enviado!">
				<f:facet name="label">
					<h:outputText value="{_KB}KB from {KB}KB uploaded --- {mm}:{ss}" />
				</f:facet>
			</rich:fileUpload>
		</h:panelGrid>
.
.
.

meu bean, Upload.java:

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

    private int uploadsAvailable = 5;
    private boolean autoUpload = false;
    private boolean useFlash = false;
    
    public Upload() {
    	System.out.println("Entrou");
    }
    
    public void upload(UploadEvent event) {  
    	 System.out.println("entrou uplod metodo");
    	       try {  
    	           String newDiretory;    
    	           ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();    
    	           ServletContext ctx = (ServletContext)externalContext.getContext();    
    	           newDiretory = ctx.getRealPath("download\\arquivos");  
    	 
    	           System.out.println(newDiretory);  
    	 
    	           UploadItem item = event.getUploadItem();  
    	           File arquivo = new File(newDiretory);  
    	           arquivo = item.getFile();  
    	 
    	           if (arquivo != null) {  
    	               arquivo.renameTo(new File(newDiretory + "/" + item.getFileName()));  
    	            }  
    	       } catch (Exception erro) {  
    	       }  
    	   }

web.xml

<?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"
	version="2.5">
	<description>Facelets StarterKit</description>
	<display-name>Dinamico</display-name>
	<context-param>
		<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
		<param-value>.xhtml</param-value>
	</context-param>
	<context-param>
		<param-name>facelets.REFRESH_PERIOD</param-name>
		<param-value>2</param-value>
	</context-param>
	<context-param>
		<param-name>facelets.DEVELOPMENT</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<context-param>
		<param-name>com.sun.faces.validateXml</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>com.sun.faces.verifyObjects</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
		<param-value>com.sun.facelets.FaceletViewHandler</param-value>
	</context-param>
	<filter>
		<display-name>Ajax4jsf Filter</display-name>
		<filter-name>ajax4jsf</filter-name>
		<filter-class>org.ajax4jsf.Filter</filter-class>

		<init-param>
			<param-name>createTempFiles</param-name>
			<param-value>false</param-value>
		</init-param>
		<init-param>
			<param-name>maxRequestSize</param-name>
			<param-value>10485760</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>ajax4jsf</filter-name>
		<servlet-name>Faces Servlet</servlet-name>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
	</filter-mapping>

	<!-- Extensions Filter 
	<filter>
		<filter-name>extensionsFilter</filter-name>
		<filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
		<init-param>
			<param-name>uploadMaxFileSize</param-name>
			<param-value>100m</param-value>
		</init-param>
		<init-param>
			<param-name>uploadThresholdSize</param-name>
			<param-value>100k</param-value>
		</init-param>
		
			<init-param> <param-name>uploadRepositoryPath</param-name>
			<param-value>/temp</param-value> <description>Set the path where the
			intermediary files will be stored. </description> </init-param>
		
	</filter> -->
	<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>*.jsf</url-pattern>
	</servlet-mapping>
	<login-config>
		<auth-method>BASIC</auth-method>
	</login-config>

	<!-- MyFaces 
	<listener>
		<listener-class>
			org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
	</listener>-->
</web-app>

faces-cong

...
<managed-bean>
  <managed-bean-name>upload</managed-bean-name>
  <managed-bean-class>idesp.sie.controller.Upload</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
 </managed-bean>
 <managed-bean>
...

16 Respostas

L

Vc colocou ele dentro de um <a4j:form> ??
se nao nao funfa msm.

C

Igweb, valeu a força, mas nem isso funfou!!!

C

Vou postar todo o meu xhtml

<?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:a4j="http://richfaces.org/a4j"
	xmlns:rich="http://richfaces.org/rich"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:c="http://java.sun.com/jstl/core">

<head>
<link rel="stylesheet" href="../css/master.css" type="text/css" />
<style type="text/css">
</style>
</head>
<body>
<a4j:form>
	<rich:panel style="background-color: #EDEDED;">

		<f:facet name="header">
			<h:outputText value="Edição da Página" />
		</f:facet>

		<h:panelGrid columnClasses="coluna1,coluna2" columns="2">
			<h:outputText value="Titulo da Página" />
			<h:inputText value="#{municipioController.htmlTitulo}" />
		</h:panelGrid>

			<rich:fileUpload fileUploadListener="#{municipioController.upload}"
				maxFilesQuantity="5" addControlLabel="Adicionar"
				clearAllControlLabel="Limpar tudo" clearControlLabel="limpar"
				stopEntryControlLabel="Parar" uploadControlLabel="Enviar"
				doneLabel="Arquivo enviado!">
				<f:facet name="label">
					<h:outputText value="{_KB}KB from {KB}KB uploaded --- {mm}:{ss}" />
				</f:facet>
			</rich:fileUpload>
		
		<rich:editor id="details_id" theme="advanced" plugins="fullscreen"
			immediate="true" value="#{municipioController.htmlOut}"
			style="margin:0 auto;" configuration="confEditor">
			<!-- 	<f:param name="theme_advanced_buttons1"
				value="fullscreen,undo,redo,cleanup,|,formatselect,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,insertdate,inserttime,hr,outdent,indent,|,link,unlink" />
			<f:param name="theme_advanced_buttons2" value="" />-->
			<f:param name="theme_advanced_toolbar_location" value="top" />
			<f:param name="theme_advanced_toolbar_align" value="left" />
			<f:param name="width" value="95%" />
			<f:param name="height" value="260" />
		</rich:editor>

		<h:panelGrid columns="2">

			<a4j:commandButton style="width:65px;" styleClass="button"
				title="Salvar" id="btnsalvar" value="Salvar"
				action="#{municipioController.btnSalvar}" />

			<a4j:commandButton style="width:65px" styleClass="button"
				title="Cancelar" id="btncancelar" value="Cancelar"
				action="#{municipioController.btnVoltarEdicao}" />
		</h:panelGrid>
	</rich:panel>
</a4j:form>
</body>
</html>
C

Alguém por favor!!!

L

este codigo esta dentro de uma view ou subView tbm?

C

uma subview…e ai alguma ajuda??

Guilherme_Gomes

Se você colocou o createTempFiles como false, não pode user o método item.getFile(), pois o arquivo ficou em memoria, não foi salvo. Para pegar o arquivo você teria que usar o item.getData() e criar o File dele, ou simplesmente colocar o createTempFiles como true.

Outra coisa:

File arquivo = new File(newDiretory); //Isso não está criando o diretório!
if(!arquivo.exists())arquivo.mkdirs(); //Isso está criando!
C

Guilherme até ai tudo bem, mas o fato é que não quer nem entrar no metodo, não quer nem imprimir o System.out.println("Entrou…);
que coloquei na primeira linha do codigo!!

Guilherme_Gomes

Percebi que você usa o MyFaces além do Richfaces. Eles tem um velho caso de conflito. Os dois precisam de um filtro para tratar os dados da requisição. O filtro que você declarar primeiro no web.xml é o que irá funcionar com upload.

Se você colocar o filtro do MyFaces primeiro, use o upload do MyFaces.
Se você colocar o filtro do Richfaces primeiro, use o upload do Richfaces.

Qualquer coisa, posta de novo.

C

Guilherme nem isso ta funfando!!! Só falta isso pra entregar o projeto!!

Guilherme_Gomes

Posta o web.xml e a página completos, por favor!

C

O web.xml completo

<?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"
	version="2.5">
	<description>Facelets StarterKit</description>
	<display-name>Dinamico</display-name>
	<context-param>
		<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
		<param-value>.xhtml</param-value>
	</context-param>
	<context-param>
		<param-name>facelets.REFRESH_PERIOD</param-name>
		<param-value>2</param-value>
	</context-param>
	<context-param>
		<param-name>facelets.DEVELOPMENT</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>
	<context-param>
		<param-name>com.sun.faces.validateXml</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>com.sun.faces.verifyObjects</param-name>
		<param-value>true</param-value>
	</context-param>
	<context-param>
		<param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
		<param-value>com.sun.facelets.FaceletViewHandler</param-value>
	</context-param>
	<filter>
		<display-name>RichFaces Filter</display-name>
		<filter-name>richfaces</filter-name>
		<filter-class>org.ajax4jsf.Filter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>richfaces</filter-name>
		<servlet-name>Faces Servlet</servlet-name>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
	</filter-mapping>
	<filter>
		<display-name>Ajax4jsf Filter</display-name>
		<filter-name>ajax4jsf</filter-name>
		<filter-class>org.ajax4jsf.Filter</filter-class>

		<init-param>
			<param-name>createTempFiles</param-name>
			<param-value>false</param-value>
		</init-param>
		<init-param>
			<param-name>maxRequestSize</param-name>
			<param-value>10485760</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>ajax4jsf</filter-name>
		<servlet-name>Faces Servlet</servlet-name>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
	</filter-mapping>
	<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>*.jsf</url-pattern>
	</servlet-mapping>
	<login-config>
		<auth-method>BASIC</auth-method>
	</login-config>
</web-app>

A pagina .xhtml

<?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:a4j="http://richfaces.org/a4j"
	xmlns:rich="http://richfaces.org/rich"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:c="http://java.sun.com/jstl/core">

<head>
<link rel="stylesheet" href="../css/master.css" type="text/css" />
<style type="text/css">
</style>
</head>
<body>
<a4j:form>
	<rich:panel style="background-color: #EDEDED;">

		<f:facet name="header">
			<h:outputText value="Edição da Página" />
		</f:facet>

		<h:panelGrid columnClasses="coluna1,coluna2" columns="2">
			<h:outputText value="Titulo da Página" />
			<h:inputText value="#{municipioController.htmlTitulo}" />
		</h:panelGrid>

		<rich:fileUpload fileUploadListener="#{upload.upload}"
			maxFilesQuantity="5" addControlLabel="Adicionar"
			clearAllControlLabel="Limpar tudo" clearControlLabel="limpar"
			stopEntryControlLabel="Parar" uploadControlLabel="Enviar"
			doneLabel="Arquivo enviado!">
			<f:facet name="label">
				<h:outputText value="{_KB}KB from {KB}KB uploaded --- {mm}:{ss}" />
			</f:facet>
		</rich:fileUpload>
		
		<rich:editor id="details_id" theme="advanced" plugins="fullscreen"
			immediate="true" value="#{municipioController.htmlOut}"
			style="margin:0 auto;" configuration="confEditor">
			<!-- 	<f:param name="theme_advanced_buttons1"
				value="fullscreen,undo,redo,cleanup,|,formatselect,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,insertdate,inserttime,hr,outdent,indent,|,link,unlink" />
			<f:param name="theme_advanced_buttons2" value="" />-->
			<f:param name="theme_advanced_toolbar_location" value="top" />
			<f:param name="theme_advanced_toolbar_align" value="left" />
			<f:param name="width" value="95%" />
			<f:param name="height" value="260" />
		</rich:editor>

		<h:panelGrid columns="2">

			<a4j:commandButton style="width:65px;" styleClass="button"
				title="Salvar" id="btnsalvar" value="Salvar"
				action="#{municipioController.btnSalvar}" />

			<a4j:commandButton style="width:65px" styleClass="button"
				title="Cancelar" id="btncancelar" value="Cancelar"
				action="#{municipioController.btnVoltarEdicao}" />
		</h:panelGrid>
	</rich:panel>
</a4j:form>
</body>
</html>
Guilherme_Gomes

A sua classe Upload implementa Serializable?
Aparece algum erro na saída?

C

Não implementa serializable, e não dá erro algum!!!

C

na mesma pagina tem o rich:editor que funciona normalmente!!

Aqui a classe Upload, ta cheia de linhas comentadas, e o metodo q tento chamar no xhtml é o upload.

package idesp.sie.controller;

import java.io.File;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

public class Upload{
    
 //   private ArrayList<File> files = new ArrayList<File>();
    private int uploadsAvailable = 5;
    private boolean autoUpload = false;
    private boolean useFlash = false;
    public int getSize() {
   /*     if (getFiles().size()>0){
            return getFiles().size();
        }else 
        {
     */       return 0;
       // }
    }

    public Upload() {
    	System.out.println("Entrou");
    }
    
    public void upload(UploadEvent event) {  
    	 System.out.println("entrou uplod metodo");
    	       try {  
    	           String newDiretory;    
    	           ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();    
    	           ServletContext ctx = (ServletContext)externalContext.getContext();    
    	           newDiretory = ctx.getRealPath("download\\arquivos");  
    	 
    	           System.out.println(newDiretory);  
    	 
    	           UploadItem item = event.getUploadItem();  
    	           File arquivo = new File(newDiretory);  
    	           arquivo = item.getFile();  
    	 
    	           if (arquivo != null) {  
    	               arquivo.renameTo(new File(newDiretory + "/" + item.getFileName()));  
    	            }  
    	       } catch (Exception erro) {  
    	       }  
    	   }  
    
 /*   public void paint(OutputStream stream, Object object) throws IOException {
        stream.write(getFiles().get((Integer)object).getData());
    }
   */ public void listener(UploadEvent event) throws Exception{
       System.out.println("Entrou listener"); 
	   UploadItem item = event.getUploadItem();
     /*   File file = new File();
        file.setLength(item.getData().length);
        file.setName(item.getFileName());
        file.setData(item.getData());
        files.add(file);
       */ uploadsAvailable--;
    }  
      
    public String clearUploadData() {
     //   files.clear();
        setUploadsAvailable(5);
        return null;
    }
    
    public long getTimeStamp(){
        return System.currentTimeMillis();
    }
    /*
    public ArrayList<File> getFiles() {
        return files;
    }

    public void setFiles(ArrayList<File> files) { 
        this.files = files;
    }
*/
    public int getUploadsAvailable() {
        return uploadsAvailable;
    }

    public void setUploadsAvailable(int uploadsAvailable) {
        this.uploadsAvailable = uploadsAvailable;
    }

    public boolean isAutoUpload() {
        return autoUpload;
    }

    public void setAutoUpload(boolean autoUpload) {
        this.autoUpload = autoUpload;
    }

    public boolean isUseFlash() {
        return useFlash;
    }

    public void setUseFlash(boolean useFlash) {
        this.useFlash = useFlash;
    }

}
Guilherme_Gomes

O que estou pensando é, por você estar usando o javax.faces.STATE_SAVING_METHOD como client, poderia dar erro se seu bean não implementar serializable!
Se não for isso, é algo realmente estranho, tenta colocar o upload sozinho numa pagina, sem estar dentro de nenhum panelGrid ou qualquer outra coisa.
Já vi do upload do richfaces dar erro em diversas ocasiões quando aninhado em outros componentes!

Criado 22 de outubro de 2009
Ultima resposta 23 de out. de 2009
Respostas 16
Participantes 3