How to use p:fileDownload to download a specific file

Asked

Viewed 856 times

0

I have a datatable and I want to implement a download button to download the pdf file from that specific line. I already managed to implement p:fileUpload and now I want to download this uploaded file.

My upload method

public void upload(FileUploadEvent evento) {
    try {
        UploadedFile arquivoUpload = evento.getFile();
        Path arquivoTemp = Files.createTempFile(null, null);
        Files.copy(arquivoUpload.getInputstream(), arquivoTemp, StandardCopyOption.REPLACE_EXISTING);
        monografia.setCaminho(arquivoTemp.toString());

        Messages.addGlobalInfo("Upload realizado com sucesso");
    } catch (IOException erro) {
        Messages.addGlobalInfo("Ocorreu um erro ao tentar realizar o upload de arquivo");
        erro.printStackTrace();
    }
}

Method salvar

public void salvar(){
    try {

        Path origem = Paths.get(monografia.getCaminho());
        Path destino = Paths.get("C:/Uploads/Monografia/" + monografia.getTitulo() + ".pdf");

        Files.copy(origem, destino, StandardCopyOption.REPLACE_EXISTING);

        cadastroMonografiaService.salvar(monografia);

        atualizarRegistros();

        messages.info("Monografia salva com sucesso!");

        RequestContext.getCurrentInstance().update(Arrays.asList("frm:monografiasDataTable", "frm:messages"));

    } catch (Exception erro) {
        messages.alerta("Erro ao salvar a Monografia!");
        erro.printStackTrace();
    }
}

2 answers

1

In your table you will have a list of objects, these objects must have the pdf or provide a way to get to it. In your view you create an attribute and a method as below:

private StreamedContent file;

//demais atributos metodos omitidos
public void fileDownload(MeuItem meuItem){
    //buscando o pdf, usar o 'meuItem' para definir a busca desse pdf
    InputStream stream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/demo/images/optimus.jpg");

    //atribuindo o pdf ao file
    file = new DefaultStreamedContent(stream, "pdf", "meupdf.pdf");
}

public StreamedContent getFile() {
    return file;
}

On your table you do it this way:

<p:dataTable id="minhaTable" var="meuItem" value="#{minhaView.meusItens}">
    <f:facet name="header">
        Basic
    </f:facet>
    <p:column headerText="Id">
        <h:outputText value="#{meuItem.id}" />
    </p:column>
    <p:column headerText="Year">
        <h:outputText value="#{meuItem.descricao}" />
    </p:column>
    <p:column headerText="Brand">
        <h:outputText value="#{meuItem.outraDescricao}" />
    </p:column>
    <p:column style="width:32px;text-align: center">
         <p:commandButton value="Download" id="blabla" actionListener="#{minhaView.fileDownload(meuItem)}">
            <p:fileDownload value="#{minhaView.file}" />
        </p:commandButton>
    </p:column>
</p:dataTable>

Reference: https://www.primefaces.org/showcase/ui/file/download.xhtml https://www.primefaces.org/showcase/ui/data/datatable/selection.xhtml

  • This thing you posted at the showcase, but I couldn’t do it. I will post my method where I save the file in a specific directory, now what I want is to get this file that will be in this directory, from the specific monograph that will be selected in the datatable

0


I resolved it this way

My method getFile

public StreamedContent getFile() throws FileNotFoundException {
    try{
        InputStream stream = new FileInputStream("C:/Uploads/Monografia/" + monografia.getTitulo() +".pdf");
        file = new DefaultStreamedContent(stream, "application/pdf", monografia.getTitulo()+".pdf");

    } catch (IOException erro) {
        messages.alerta("Não foi possível fazer o download da Monografia ");
        erro.printStackTrace();
    }
    return file;
}

Component fileDownload

            <p:column headerText="Download">
                <p:commandButton immediate="true" value="Download" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop);" icon="ui-icon-arrowthick-1-s">
                    <p:fileDownload value="#{gestaoMonografiasBean.file}" />
                </p:commandButton>
            </p:column>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.