日期:2014-05-16 浏览次数:20356 次
?
package org.primefaces.component.filedownload;
?
import java.io.IOException;
?
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.faces.component.StateHolder;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.servlet.http.HttpServletResponse;
?
import org.primefaces.model.StreamedContent;
?
public class FileDownloadActionListener implements ActionListener, StateHolder {
?
private ValueExpression value;
private ValueExpression contentDisposition;
public FileDownloadActionListener() {}
public FileDownloadActionListener(ValueExpression value, ValueExpression contentDisposition) {
this.value = value;
this.contentDisposition = contentDisposition;
}
?
public void processAction(ActionEvent actionEvent) throws AbortProcessingException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
String contentDispositionValue = contentDisposition != null ? (String) contentDisposition.getValue(elContext) : "attachment";
StreamedContent content = (StreamedContent) value.getValue(elContext);
try {
? ?String fileName = java.net.URLEncoder.encode(content.getName(), "UTF-8");?
? ?response.setCharacterEncoding("UTF-8");
response.setContentType(content.getContentType());
response.setHeader("Content-Disposition", contentDispositionValue + ";filename=" + fileName);
byte[] buffer = new byte[2048];
int length;
while ((length = (content.getStream().read(buffer))) >= 0) {
response.getOutputStream().write(buffer, 0, length);
}
response.setStatus(200);
content.getStream().close();
response.getOutputStream().flush();
facesContext.responseComplete();
}catch (IOException e) {
e.printStackTrace();