JSF文件下载2

不说别的了,上代码
首先流获得
 public static ByteArrayOutputStream downloadFile(String fileName) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bos = null;
        try {
            fis = new java.io.FileInputStream(fileName);
            bis = new BufferedInputStream(fis);
            baos = new ByteArrayOutputStream();
            bos = new BufferedOutputStream(baos);
        } catch (FileNotFoundException ex) {
            java.util.logging.Logger.getLogger(DownloadUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {

            //解决中文文件名的问题
//                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");

            byte[] b = new byte[1024];
            int i = 0;

            while ((i = bis.read(b)) > 0) {
                bos.write(b, 0, i);
            }
            bos.flush(); //提交文件流,很关键
            bis.close();

        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(DownloadUtil.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(DownloadUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
            return baos;
        }

    }

有了文件流之后,以此和欲保存的文件名作为参数传到这个函数:
   public static void downloadAction(String fileName,ByteArrayOutputStream baos) {
        try {

            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls"); //不是内嵌显示(inline),而是作为附件下载
            response.setContentLength(baos.size());
            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream sos = response.getOutputStream();           
            baos.writeTo(sos);    
        sos.flush();
          baos.close();
        } catch (IOException ex) {
            logger.debug(ex);
        }
    }

你可能感兴趣的:(java,.net,JSF,Excel)