I have a datatable which allows you to download files. It works. However when I try to download a file after filtering returned is first on the list.
This image shows that when clicked on teste4.txt the same file was downloaded. This is correct.
This other picture shows that when clicked on file teste4.txt, after filtering, the downloaded file was teste1.txt
This is my file containing the datatable:
<h:form id="hFormListaArquivosRegiao2" enctype="multipart/form-data">
<p:dataTable id="pDataTableListaArquivos" var="arquivo" value="#{arquivoBean.listaArquivos}" filteredValue="#{arquivoBean.filteredListaArquivos}">
<p:column id="pColumnNomeArquivo" headerText="#{msg.NomeDoArquivo}" sortBy="#{arquivo.nomeArquivo}" filterMatchMode="contains" filterBy="#{arquivo.nomeArquivo}">
<h:commandLink action="#{arquivoBean.download}" title="#{arquivo.nomeArquivo}">
<h:outputText value="#{arquivo.nomeArquivo}" />
<f:setPropertyActionListener target="#{arquivoBean.arquivo}" value="#{arquivo}" />
</h:commandLink>
</p:column>
</h:form>
This is the method of backingBean responsible for downloading:
public void download() throws Exception {
logger.debug("NOME ARQUIVO: "+ ContextoBean.CAMINHO_ARQUIVOS + arquivo.getNomeArquivo() +", "+ arquivo.getNomeArquivo());
FacesContext facesContext = FacesContext.getCurrentInstance();
pushArquivo(facesContext.getExternalContext(), ContextoBean.CAMINHO_ARQUIVOS + arquivo.getNomeArquivo(), arquivo.getNomeArquivo());
facesContext.responseComplete();
}
This is the helper method of backingBean responsible for downloading:
private void pushArquivo(ExternalContext externalContext, String nomeArquivo, String nomeDeExibicao) throws IOException {
// Info sobre a lógica usada: http://stackoverflow.com/questions/1686821/execute-backing-bean-action-on-load
File descritoArquivo = new File(nomeArquivo);
int length = 0;
OutputStream os = externalContext.getResponseOutputStream();
String extencaoArquivo = externalContext.getMimeType(nomeArquivo);
externalContext.setResponseContentType((extencaoArquivo != null) ? extencaoArquivo : "application/octet-stream");
externalContext.setResponseContentLength((int) descritoArquivo.length());
externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + nomeDeExibicao + "\"");
// Stream to the requester.
byte[] bbuf = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(descritoArquivo));
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
os.write(bbuf, 0, length);
}
in.close();
}