JSF 文件下载

最近的项目上用到的是JSF,需求是做一个页面在的下载,实现可以下载文件到客户端。并且和单独的文件下载不同的是,此下载是ZIP文件,就是先把指定目录下的文件先压缩,再进行页面下载。具体代码如下:
/**
* 程序自动打包
* @throws IOException
*/
public String getZipData(String fileName) throws IOException{
ZipOutputStream zos = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
 
String zipFileName = ""; //--压缩的文件名
String realInputFilePath = ""; //--压缩文件输入流路径
try{
String realNewFilePath = "d:/xxx"; //--压缩文件的路径
zipFileName = realNewFilePath + fileName + ".zip";
 
realInputFilePath ="e:/xxx"; //--要压缩文件的路径
 
File directory = new File(realInputFilePath);
File[] files = directory.listFiles(); //--得到指定目录下所有文件名
if(null != files){
int fileLen = files.length;
 
fos = new FileOutputStream(zipFileName); //--打包后路径+ 文件名
dos = new DataOutputStream(fos);
zos = new ZipOutputStream(dos); //--定义zip输流
 
for(int i=0; i<fileLen; i++){
FileInputStream fis = null;
DataInputStream dis = null;
String tempfilePath = files[i].getAbsolutePath();  //--得到每个文件绝对路径+ 文件名
 
fis = new FileInputStream(tempfilePath);
dis = new DataInputStream(fis);
zos.putNextEntry(new ZipEntry(tempfilePath));
zos.setEncoding("UTF-8");    //--指定编码,否则文件名乱码
 
int c=0;
while((c=dis.read()) != -1){
zos.write(c);
}
zos.closeEntry();
if(null != fis){
fis.close();
}
if(null != dis){
dis.close();
}
}
}
}catch(Exception e){
e.printStackTrace();
} finally{
if(null != zos){
zos.close();
}
if(null != dos){
dos.close();
}
if(null != fos){
fos.close();
}
}
return zipFileName;
}
 在action中调用此方法
 String zipFileName = batchDownloadService.getZipData();  //--进行文件的自动打包
batchDownloadService.downloadFile(zipFileName,fileName,pagebatchDownloadModel);  //--下载文件到客户端
 dao中的方法:
 /**
* 下载文件到客户端
*/
public void downloadFile(String zipFileName,String fileName,BatchDownloadModel pagebatchDownloadModel){
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
try{
File zipFile = new File(zipFileName);
 
if(zipFile.exists()){
ServletOutputStream outstream =response.getOutputStream();
FileInputStream fis = new FileInputStream(zipFile);
String downloadZipName = fileName+"_"+"xx年_" + "xx月_" +".zip";
 
response.setContentType("application/zip");
response.setHeader("Transfer-Encoding", "chunked");
response.addHeader("Content-disposition", "attachment;filename="+new String(downloadZipName.getBytes("GB2312"),"ISO8859-1") );
BufferedInputStream bufInStrm = new BufferedInputStream (fis);
 
int readBytes = 0;
int bufferSize = 8192;
byte[] buffer = new byte[bufferSize];
while ((readBytes = bufInStrm.read(buffer)) != -1){
if (readBytes == bufferSize) {
 outstream.write(buffer);
}else{
 outstream.write(buffer, 0, readBytes);
}
outstream.flush();
response.flushBuffer();
}
 
fis.close();
outstream.close();
FacesContext.getCurrentInstance().responseComplete(); //--非常关键,否则提示文件损坏
}else{
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
//response.getWriter().write("<script type='text/javascript'>alert('当前条件未查询到任何数据!')</script>");
response.getWriter().write("<script>location.href='"+request.getContextPath() + "/faces/sysMag/batchDownload/downloadFail. jsp"+"'</script>");
FacesContext.getCurrentInstance().responseComplete(); //--非常关键,否则提示文件损坏
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 删除指定文件夹目录即目录中文件
*/
public void deleteDir(File dir) {
   if (dir == null || !dir.exists() || !dir.isDirectory())  //-- 检查参数
       return;
   for (File file : dir.listFiles()) {
       if (file.isFile())
           file.delete();   //--删除所有文件
       else if (file.isDirectory())
           deleteDir(file);    //--递规的方式删除文件夹
   }
   dir.delete(); //--删除目录本身
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSF实现文件的下载功能 public static void downloadFile(String path,String fileName) { try { // 获得JSF上下文环境 FacesContext context = FacesContext.getCurrentInstance(); // 获得ServletContext对象 ServletContext servletContext = (ServletContext) context .getExternalContext().getContext(); // 取得文件的绝对路径 String realName = servletContext.getRealPath(path) + "/" + fileName; HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext .getCurrentInstance().getExternalContext().getResponse(); downloadFile(httpServletResponse,realName,fileName); } catch (IOException e) { e.printStackTrace(); } FacesContext.getCurrentInstance().responseComplete(); } public static void downloadFile(HttpServletResponse response,String realName,String fileName) throws IOException { response.setHeader("Content-disposition", "attachment; filename=" + fileName); response.setContentType("application/x-download"); //File exportFile = new File(realName); //response.setContentLength((int) exportFile.length()); ServletOutputStream servletOutputStream = response.getOutputStream(); byte[] b = new byte[1024]; int i = 0; FileInputStream fis = new java.io.FileInputStream(realName); while ((i = fis.read(b)) > 0) { servletOutputStream.write(b, 0, i); } } 使用方法 1、在backing bean的方法中调用函数1即可。如Abean中download方法调用了该方法,前台可以这样调用: 或者 2、jsp页面可以这样调用: <% String filename = ""; if (request.getParameter("filename") != null) { filename = request.getParameter("filename"); } try { framewo
依赖的文件: tomahawk-1.1.3.jar commons-fileupload-1.2.jar commons-io-1.3.1.jar Tomahawk.tld 把这个三个包放在/WEB_INF/lib目录下面。Jsf依赖的包也放在这个目录下面 Tomahawk.tld放在/WEB-INF目录下。Jsf标签也放在这个目录下面。 这个主要讲jsf上传文件,因此只罗列了上传文件用到的包和标签。 Web-xml文件如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <!-- Context Listener creates and sets the application handler --> <!-- Faces Servlet --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Faces Servlet Mapping --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <filter> <filter-name>ExtensionsFilter</filter-name> <filter-class> org.apache.myfaces.component.html.util.ExtensionsFilter </filter-class> <init-param> <param-name>uploadMaxFileSize</param-name> <param-value>10m</param-value> </init-param> <init-param> <param-name>uploadThresholdSize</param-name> <param-value>100k</param-value> </init-param> </filter> <filter-mapping> <filter-name>ExtensionsFilter</filter-name> <!—要和<servlet-mapping>中的<servlet-name>一致--> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> 上传文件的页面如下: <%@ include file="tags.jsp"%> <f:view> <h:form id="MyForm" enctype="multipart/form-data" > <h:messages globalOnly="true" styleClass="message"/> <h:panelGrid columns="3" border="0" cellspacing="5"> <h:outputLabel for="myFileId" value="File: "/> <x:inputFileUpload id="myFileId" value="#{myBean.myFile}" storage="file" required="true"/> <h:message for="myFileId"/> <h:outputLabel for="myParamId" value="Param: "/> <h:selectOneMenu id="myParamId" value="#{myBean.myParam}" required="true"> <f:selectItem itemLabel="" itemValue=""/> <f:selectItem itemLabel="MD5" itemValue="MD5"/> <f:selectItem itemLabel="SHA-1" itemValue="SHA-1"/> <f:selectItem itemLabel="SHA-256" itemValue="SHA-256"/> <f:selectItem itemLabel="SHA-384" itemValue="SHA-384"/> <f:selectItem itemLabel="SHA-512" itemValue="SHA-512"/> </h:selectOneMenu> <h:message for="myParamId"/> <h:outputText value=" "/> <h:commandButton value="Submit" action="#{myBean.processMyFile}"/> <h:outputText value=" "/> </h:panelGrid> </h:form> </f:view> 其中tags.jsp文件如下: <%@ page language="java" pageEncoding="GB18030"%> <%@ page contentType="text/html" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="x"%> Faces-config.xml文件如下: <faces-config> <managed-bean> <managed-bean-name>myBean</managed-bean-name> <managed-bean-class> fileupload.MyBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config> MyBean如下: package com.dhc; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.apache.myfaces.custom.fileupload.UploadedFile; public class oaMailMainForm { private UploadedFile myFile; public UploadedFile getMyFile() { return myFile; } public void setMyFile(UploadedFile myFile) { this.myFile = myFile; } public String uploadedfile() { System.out.println("Entry"); try { InputStream in = new BufferedInputStream(myFile.getInputStream()); try { byte[] buffer = new byte[64 * 1024]; FileOutputStream fileOutputStream = new FileOutputStream( "C:\\My Files\\tst.jpg");// 这里可以把上传的文件写服务器目录,或者数据库中 while (in.read(buffer) > 0) { fileOutputStream.write(buffer); } } finally { in.close(); } System.out.println("End"); return "success"; } catch (Exception x) { System.out.print("Exception"); FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_FATAL, x.getClass().getName(), x .getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); return null; } } } 参考文献:http://www.blogjava.net/cooky/archive/2007/10/02/150176.html http://blog.csdn.net/meteorlWJ/archive/2008/01/09/2032505.aspx http://tml808.javaeye.com/blog/166853
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值