June 23 2016

Jsf download file example

Jsf download file example


<!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:f="http://java.sun.com/jsf/core">

<h:head>
<title> Jsf File Download </title>
</h:head>

<h:body>

<h:form>

<h3> Jsf File Download </h3>

<h:commandButton value="Submit" actionListener="#{jsfFileDownload.download}" />

</h:form>
</h:body>

</html>


package com.answersz.jsf;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

@ManagedBean(name = "jsfFileDownload")
@SessionScoped
public class JsfFileDownload {

public void download() throws IOException {

// Get the file from specific location or database
File file = new File("C:\\Users\\amruth\\Desktop\\Amruth1.pdf");

FacesContext facesContext = FacesContext.getCurrentInstance();

HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();

response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setHeader("Content-Type", "application/pdf");

OutputStream outputStream = response.getOutputStream();

FileInputStream fileInputStream = new FileInputStream(file);

byte[] bytesBuffer = new byte[2048];

int bytesRead = 0;

while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0) {
outputStream.write(bytesBuffer, 0, bytesRead);
}

outputStream.flush();

fileInputStream.close();
outputStream.close();

facesContext.responseComplete();
}

}

 


Copyright © 2014. All rights reserved.

Posted June 23, 2016 by answersz in category Jsf

Leave a Comment

Your email address will not be published. Required fields are marked *

*