FileDownload is used to stream binary contents like files stored in database to the client. FileDownload is used by attaching it to any Faces command component like button or a link. Additionally, presentation of download can be configured with the contentDisposition attribute that takes either "attachment" or "inline" as a value. When "inline" is used, the browser tries to open the file within itself if supported instead of downloading. Use "inline" together with the attribute store="true" to make sure that the opened file is proposed to be saved with its original name if the opened file shall be saved. Otherwise, Chrome and Edge, will use the screen's name as default for the file save.
<script>
//<![CDATA[
function start() {
PF('statusDialog').show();
}
function stop() {
PF('statusDialog').hide();
}
//]]>
</script>
<div class="card">
<p:dialog modal="true" widgetVar="statusDialog" header="Status" draggable="false" closable="false"
resizable="false">
<i class="pi pi-spinner pi-spin" style="font-size:3rem"></i>
</p:dialog>
<h:form>
<p:commandButton value="Download" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop);"
icon="pi pi-arrow-down" styleClass="mr-2">
<p:fileDownload value="#{fileDownloadView.file}"/>
</p:commandButton>
<p:commandButton value="Inline Download" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop);"
icon="pi pi-arrow-down" styleClass="mr-2">
<p:fileDownload value="#{fileDownloadView.file}" contentDisposition="inline" store="true" />
</p:commandButton>
<p:commandButton value="Ajax Download" icon="pi pi-arrow-down" styleClass="ui-button-outlined">
<p:fileDownload value="#{fileDownloadView.file}"/>
</p:commandButton>
</h:form>
</div>
package org.primefaces.showcase.view.file;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Named;
@Named
@RequestScoped
public class FileDownloadView {
private StreamedContent file;
public FileDownloadView() {
file = DefaultStreamedContent.builder()
.name("downloaded_boromir.jpg")
.contentType("image/jpg")
.stream(() -> FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/resources/demo/images/boromir.jpg"))
.build();
}
public StreamedContent getFile() {
return file;
}
}