Download de arquivo com JSF não está funcionando

E ai pessoal,

Estou com um sério problema com o download de arquivos com o JSF. Sei que existem vários tópicos que mencionam o mesmo assunto porém não vi ngm com esse erro estranho que acontece cmg.

Resumo:

Tenho um datatable e com os dados do mesmo preciso fazer um download de um arquivo “.xls”. Possuo um método que gera o arquivo normalmente e coloca numa pasta dentro do meu contexto web. Até ai tudo perfeito. Só que quando chamo o método pra fazer o download, ao invés de aparecer um dialog box pra salvar o arquivo está aparecendo umá página cheia de caracteres estranhos.

Será que algum de vcs tem alguma ideia pra solucionar esse mistério ?

Segue o meu método responsável pela lógica de download:

[code] /**
* Download a XLS file representing the deliveries filtered.
*
* @throws Exception
*/

public void downloadXLS() throws Exception {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ec = context.getExternalContext();
HttpServletResponse response = (HttpServletResponse) ec.getResponse();

  File file = new File(regDoc.getAbsolutePath());
  if (!file.exists()) {
     log.warn("[ListDocumentGenerator - " + getCurrentLoggedUser().getUserid() + "] File '" + regDoc.getName() + "' doesn't exists.");
     return;
  }
  if (!file.canRead()) {
     log.warn("[ListDocumentGenerator - " + getCurrentLoggedUser().getUserid() + "] File '" + regDoc.getName() + "' can't be read.");
     return;
  }
  // Verify if the size is within the limit of the response
  long size = file.length();
  int sizeInt = (int) size;
  if (size != (long) sizeInt) {
     log.warn("[ListDocumentGenerator - " + getCurrentLoggedUser().getUserid() + "] Size of the file '" + regDoc.getName() + "' (" + size + " bytes) doesn't fit the response's maximum size.");
     return;
  }

  // Define the response length and type
  response.setContentLength(sizeInt);
  // see: http://www.w3schools.com/media/media_mimeref.asp
  response.setContentType("application/vnd.ms-excel");
  response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");  

  BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
  BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

  // Write the file's content to the response
  byte[] b = new byte[sizeInt];
  while (in.available() > 0) {
     int qtty = in.read(b);
     out.write(b, 0, qtty);
  }

  log.info("[ListDocumentGenerator - " + getCurrentLoggedUser().getUserid() + "] File '" + regDoc.getName() + "' (" + sizeInt + " bytes) was downloaded sucessfully.");

  // Flush and close
  in.close();
  out.flush();
  out.close();

  FacesContext.getCurrentInstance().responseComplete();

}
[/code]

Any ideas ??? :roll:

Boa noite,

Tenta mudar o ContentType para outro tipo de arquivo… para verificar se ele vai fazer a mesma coisa

Att,

[quote=ekszuki]Boa noite,

Tenta mudar o ContentType para outro tipo de arquivo… para verificar se ele vai fazer a mesma coisa

Att,
[/quote]

Já tentei de tudo… mudei o content type pra application/xls, application/excel… e por ai vai… continua com a mesma coisa =(

Normalmente esta parada é content-type.

Qnd vc alterou o conten-type e não funcionou,
você apagou o cache do browser, reiniciou o container, …? Fez este tipo de coisa pra garantir q a sua alteração valeu?

[quote=fvslistas]Normalmente esta parada é content-type.

Qnd vc alterou o conten-type e não funcionou,
você apagou o cache do browser, reiniciou o container, …? Fez este tipo de coisa pra garantir q a sua alteração valeu?[/quote]

Eu criei outro war, reiniciei o server, limpei o cache e os cookies e nada… =(

Eu utilizo o JSF sem cookies… com o jsessionid na URL… n sei se isso tem a ver…

http://wiki.metawerx.net/wiki/Web.xml.MimeMapping
Tente isto

<mime-mapping> 
    <extension>xls</extension> 
    <mime-type>application/vnd.ms-excel</mime-type> 
</mime-mapping>

no web.xml

[quote=fvslistas]http://wiki.metawerx.net/wiki/Web.xml.MimeMapping
Tente isto

<mime-mapping> 
    <extension>xls</extension> 
    <mime-type>application/vnd.ms-excel</mime-type> 
</mime-mapping>

no web.xml[/quote]

Boa dica cara… mas mesmo adicionando isso ainda tá dando o problema… Segue abaixo meu web.xml

[code]<?xml version=“1.0” encoding=“UTF-8”?>
<web-app id=“myApp” version=“2.4” xmlns=“http://java.sun.com/xml/ns/j2ee
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=“http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>

&lt;description&gt;My App&lt;/description&gt;
&lt;display-name&gt;myApp&lt;/display-name&gt;
&lt;context-param&gt;
	&lt;description&gt;
		Monitors Faces JSP files for modifications and synchronizes a running server with the changes without restarting the server. If this parameter is set to false or removed from the
		deployment descriptor, any changes made to Faces JSP files may not be seen by the server until it is restarted. This parameter is usually set to true while the Faces JSP files are being
		developed and debugged in order to improve the performance of the development environment.
	&lt;/description&gt;
	&lt;param-name&gt;com.ibm.ws.jsf.JSP_UPDATE_CHECK&lt;/param-name&gt;
	&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
	&lt;description /&gt;
	&lt;param-name&gt;com.ibm.ws.jsf.LOAD_FACES_CONFIG_AT_STARTUP&lt;/param-name&gt;
	&lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
	&lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt;
	&lt;param-value&gt;server&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
	&lt;param-name&gt;org.richfaces.SKIN&lt;/param-name&gt;
	&lt;param-value&gt;#{skinMBean.skin}&lt;/param-value&gt;
&lt;/context-param&gt;


&lt;context-param&gt;
	&lt;param-name&gt;org.richfaces.CONTROL_SKINNING&lt;/param-name&gt;
	&lt;param-value&gt;enable&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;context-param&gt;
	&lt;param-name&gt;org.richfaces.CONTROL_SKINNING_LEVEL&lt;/param-name&gt;
	&lt;param-value&gt;basic&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;context-param&gt;
	&lt;description&gt;
	   This configuration tells the ContextLoaderListener where to find the Spring context, thus enabling the startup of
	   the Spring context at webserver startup.
	&lt;/description&gt;
	&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
	&lt;param-value&gt;
     	classpath*:applicationContext.xml
        classpath*:applicationContext-dataSource.xml
        classpath*:applicationContext-security-web.xml
        classpath*:applicationContext-aspects.xml
        classpath*:applicationContext-validation.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;

&lt;filter&gt;
	&lt;filter-name&gt;CustomCharacterEncodingFilter&lt;/filter-name&gt;
	&lt;filter-class&gt;de.kybeidos.mmw.jsf.CharsetEncodeFilter&lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter&gt;
	&lt;filter-name&gt;UrlSessionFilter&lt;/filter-name&gt;
	&lt;filter-class&gt;de.kybeidos.mmw.jsf.UrlSessionFilter&lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter&gt;
	&lt;filter-name&gt;OSIVFilter&lt;/filter-name&gt;
	&lt;filter-class&gt;
		org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&lt;/filter-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;singleSession&lt;/param-name&gt;
		&lt;param-value&gt;true&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;sessionFactoryBeanName&lt;/param-name&gt;
		&lt;param-value&gt;sessionFactory&lt;/param-value&gt;
	&lt;/init-param&gt;
&lt;/filter&gt;

&lt;filter&gt;
	&lt;filter-name&gt;Acegi Filter Chain Proxy&lt;/filter-name&gt;
	&lt;filter-class&gt;org.acegisecurity.util.FilterToBeanProxy&lt;/filter-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;targetClass&lt;/param-name&gt;
		&lt;param-value&gt;org.acegisecurity.util.FilterChainProxy&lt;/param-value&gt;
	&lt;/init-param&gt;
&lt;/filter&gt;


&lt;filter-mapping&gt;
	&lt;filter-name&gt;CustomCharacterEncodingFilter&lt;/filter-name&gt;
	&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;

&lt;filter-mapping&gt;
	&lt;filter-name&gt;UrlSessionFilter&lt;/filter-name&gt;
	&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;

&lt;filter-mapping&gt;
	&lt;filter-name&gt;OSIVFilter&lt;/filter-name&gt;
	&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;

&lt;filter-mapping&gt;
	&lt;filter-name&gt;Acegi Filter Chain Proxy&lt;/filter-name&gt;
	&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;

&lt;listener&gt;
	&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;

&lt;listener&gt;
	&lt;listener-class&gt;com.sun.faces.config.ConfigureListener&lt;/listener-class&gt;
&lt;/listener&gt;

&lt;!-- commented because ibm libraries was removed --&gt;
&lt;!--	&lt;servlet id="Servlet_1108413200548"&gt;--&gt;
&lt;!--		&lt;servlet-name&gt;JS Resource Servlet&lt;/servlet-name&gt;--&gt;
&lt;!--
	&lt;servlet-class&gt;com.ibm.faces.webapp.JSResourceServlet&lt;/servlet-class&gt;
--&gt;
&lt;!--		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;--&gt;
&lt;!--	&lt;/servlet&gt;--&gt;

&lt;servlet id="Servlet_1108413201740"&gt;
	&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
	&lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;servlet&gt;
	&lt;servlet-name&gt;DownloadServlet&lt;/servlet-name&gt;
	&lt;servlet-class&gt;de.kybeidos.mmw.util.servlet.DownloadServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/faces/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
	&lt;url-pattern&gt;*.faces&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;DownloadServlet&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/servlet/download&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;

&lt;filter&gt;
	&lt;display-name&gt;Ajax4jsf Filter&lt;/display-name&gt;
	&lt;filter-name&gt;ajax4jsf&lt;/filter-name&gt;
	&lt;filter-class&gt;org.ajax4jsf.Filter&lt;/filter-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;createTempFiles&lt;/param-name&gt;
		&lt;param-value&gt;false&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;maxRequestSize&lt;/param-name&gt;
		&lt;param-value&gt;512000&lt;/param-value&gt;
	&lt;/init-param&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
	&lt;filter-name&gt;ajax4jsf&lt;/filter-name&gt;
	&lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
	&lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;
	&lt;dispatcher&gt;FORWARD&lt;/dispatcher&gt;
	&lt;dispatcher&gt;INCLUDE&lt;/dispatcher&gt;
&lt;/filter-mapping&gt;

&lt;mime-mapping&gt;
	&lt;extension&gt;xls&lt;/extension&gt;
	&lt;mime-type&gt;application/vnd.ms-excel&lt;/mime-type&gt;
&lt;/mime-mapping&gt;

&lt;mime-mapping&gt;
	&lt;extension&gt;pdf&lt;/extension&gt;
	&lt;mime-type&gt;application/pdf&lt;/mime-type&gt;
&lt;/mime-mapping&gt;

&lt;session-config&gt;
	&lt;session-timeout&gt;90&lt;/session-timeout&gt;
&lt;/session-config&gt;
&lt;welcome-file-list&gt;
	&lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
&lt;/welcome-file-list&gt;
&lt;error-page&gt;
	&lt;error-code&gt;500&lt;/error-code&gt;
	&lt;location&gt;/faces/open/error.jsp&lt;/location&gt;
&lt;/error-page&gt;
&lt;error-page&gt;
	&lt;error-code&gt;404&lt;/error-code&gt;
	&lt;location&gt;/faces/open/error.jsp&lt;/location&gt;
&lt;/error-page&gt;
&lt;error-page&gt;
	&lt;exception-type&gt;javax.faces.application.ViewExpiredException&lt;/exception-type&gt;
	&lt;location&gt;/faces/open/newAuthentication.jsp&lt;/location&gt;
&lt;/error-page&gt;

</web-app>
[/code]

Alguém pode me ajudar ?? Ainda nao consegui resolver esse problema… :?

Cara consegui resolver o problema… o botão que chamava um actionListener era a4j:commandButton. Mudei para h:commandButton e aí funcionou. Só descobri isso pq tinha uma parte da minha aplicação que fazia uma lógica parecida, senao ia fica mudando codigo e nao ia descobrir nunca…

Valeu pela ajuda

Eu só conseguia pensar em mime e coisas do tipo. Nunca ia pensar na mudança do botão. :slight_smile:
Que bom que conseguiu, parabéns e obrigado por postar a solução.