response.setHeader("Cache-Control", "public"); response.setHeader("Pragma", "public"); //response.setHeader("Content-Disposition", "attachment; filename=" + docName+".pdf"); response.setContentType("application/pdf"); String reportBasePath = ServletActionContext.getServletContext().getRealPath(DOWNLOADFILEPATH); //System.out.println("reportBasePath....is : "+reportBasePath); String template = reportBasePath+"/"+"convenientVisa.jasper"; //System.out.println("template....is : "+template); String reportOutputBasePath = ServletActionContext.getServletContext().getRealPath(DOWNLOADFILEPATH); String pdfCn = ReportUtil.createReportName(pdfNameCn,reportType); String pdfEn = ReportUtil.createReportName(pdfNameEn,reportType); String outputFileCn = reportOutputBasePath +"/"+ pdfCn; String outputFileEn = reportOutputBasePath +"/"+ pdfEn; //System.out.println("outputFileCn....is : "+outputFileCn); //System.out.println("outputFileEn....is : "+outputFileEn); if(!new File(template).exists()){ //System.out.println("报表模版不存在"); throw new Exception("报表模版不存在"); } File reportOutputBaseFile = new File(reportBasePath + reportOutputBasePath); if(!reportOutputBaseFile.exists())reportOutputBaseFile.mkdirs(); //确定要导出的文件的名称 if(url.indexOf("/cn/")>-1){ ReportUtil.exportReports(ffpTravelDetailList, reportParameter,ReportUtil.REPORT_FORMAT_PDF,template, outputFileCn); }else{ ReportUtil.exportReports(ffpTravelDetailList, reportParameter,ReportUtil.REPORT_FORMAT_PDF,template, outputFileEn); } //InputStream in = ServletActionContext.getServletContext().getResourceAsStream(outputFile); public boolean regex(String regex, String str) { Pattern p = Pattern.compile(regex, Pattern.MULTILINE); Matcher m = p.matcher(str); return m.find(); }
获取登录用户以及链接地址:
LpAccount user=(LpAccount) ActionContext.getContext().getSession().get("user");//获取登录用户名 String url = ServletActionContext.getRequest().getRequestURL().toString();//获取响应的链接地址
获取文件,这个必须有:
// 从下载文件原始存放路径读取得到文件输出流
public InputStream getDownloadFile() { String url = ServletActionContext.getRequest().getRequestURL().toString(); if(url.indexOf("/cn/")>-1){ return ServletActionContext.getServletContext().getResourceAsStream( DOWNLOADFILEPATH + pdfNameCn+".pdf"); }else{ return ServletActionContext.getServletContext().getResourceAsStream( DOWNLOADFILEPATH + pdfNameEn+".pdf"); } }
ReportUtil.java
package com.csair.skypearl.utils; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JRExporter; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter; import net.sf.jasperreports.j2ee.servlets.ImageServlet; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.struts2.ServletActionContext; public class ReportUtil { public static final String REPORT_FORMAT_XLS = "XLS"; public static final String REPORT_FORMAT_XLSX = "XLSX"; public static final String REPORT_FORMAT_DOC = "DOC"; public static final String REPORT_FORMAT_PDF = "PDF"; public static final String REPORT_FORMAT_HTML = "HTML"; /** * <B>导出报表</B><br /> * create by:vakin * at:2011-1-7 * @param <T> * @param reportDatas * @param parameters * @param exportType * @param template * @param outputFile * @throws Exception */ @SuppressWarnings("unchecked") public static <T> void exportReports(List<T> reportDatas, Map parameters,String exportType, String template, String outputFile) throws Exception { //HttpServletRequest request = ServletActionContext.getRequest(); JasperReport jasperreport = DynamicColumnReport.dynamicColumnReport( null, template); //根据参数判断是否需要动态生成列 JasperPrint print = JasperFillManager.fillReport(jasperreport,parameters,new JRBeanCollectionDataSource(reportDatas)); JRExporter exporter = null; if(REPORT_FORMAT_XLS.equalsIgnoreCase(exportType)){ exporter = new JRXlsExporter(); }else if(REPORT_FORMAT_DOC.equalsIgnoreCase(exportType)){ exporter = new JRDocxExporter(); }else if(REPORT_FORMAT_PDF.equalsIgnoreCase(exportType)){ exporter = new JRPdfExporter(); }else if(REPORT_FORMAT_HTML.equalsIgnoreCase(exportType)){ exporter = new JRHtmlExporter(); }else if(REPORT_FORMAT_XLSX.equalsIgnoreCase(exportType)){ exporter = new JRXlsxExporter(); } exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outputFile); exporter.setParameter(JRExporterParameter.JASPER_PRINT, print); exporter.exportReport(); } /** * <B>输出报表图</B><br /> * create by:vakin * at:2011-1-7 * @param <T> * @param reportDatas * @param parameters * @param template * @throws Exception */ @SuppressWarnings("unchecked") public static <T> void createReportChart(List<T> reportDatas, Map parameters, String template) throws Exception { HttpServletResponse response = ServletActionContext.getResponse(); PrintWriter printWriter = response.getWriter(); JasperPrint jasperPrint = JasperFillManager.fillReport(template, new HashMap(), new JRBeanCollectionDataSource(reportDatas)); JRHtmlExporter htmlExporter = new JRHtmlExporter(); response.setContentType("text/html"); ServletActionContext.getRequest().getSession().setAttribute( ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint); htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); htmlExporter.setParameter(JRExporterParameter.OUTPUT_WRITER, printWriter); htmlExporter.setParameter( JRHtmlExporterParameter.CHARACTER_ENCODING, "utf-8"); String imageUrl = "reportChart?__r="+ System.currentTimeMillis() +"&image="; htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl); htmlExporter.exportReport(); printWriter.flush(); printWriter.close(); } public static String getReportBasePath(){ return ServletActionContext.getServletContext().getRealPath("/jasreportTemplete/"); } public static String createReportName(String modelName,String docType){ return modelName + "."+docType.toLowerCase(); } }
值得注意的是:对于ie7及以下版本的浏览器必须设置浏览器相应头的缓存设置:
网上有解释:This is a typical MSIE error message when a download is been provided over HTTPS (SSL) while the response headers are been set to disable the browser cache
添加的代码:
response.setHeader("Cache-Control", "public"); response.setHeader("Pragma", "public");
对于火狐浏览器,有可能文件名过长,而背截取,导致文件类型错误,无法下载打开等,可以作如下设置:
String browser = this.getRequest().getHeader("User-Agent"); if(browser != null && browser.indexOf("MSIE") == -1) { if(!(url.indexOf("/cn/")>-1)){ docmNameEn = "=?UTF-8?B?" + (new String (Base64.encodeBase64(docmNameEn.getBytes("UTF-8")))) + "?="; } }
struts2配置文件:
<param name="fileName">${docNameEn}.pdf</param> <result name="download" type="stream"> <!-- 下载文件类型定义 --> <param name="contentType">application/pdf</param> <!-- 下载文件处理方法 --> <param name="contentDisposition"> attachment;filename="${docNameEn}.pdf" </param> <!-- 下载文件输出流定义 --> <param name="inputName">downloadFile</param> </result>
对于中文文件名的处理:
String docmName=new String(new String(pdfNameCn).getBytes("GBK"),"ISO8859-1"); String docmNameEn = new String(new String(pdfNameEn).getBytes("GBK"),"ISO8859-1");
struts2的一些配置也可以直接在java类里面设置:
response.setHeader("Content-Disposition", "attachment; filename=" + docName+".pdf");//[color=red]attachment表示下载,inline表示在线查看[/color] response.setContentType("application/pdf");//文件格式设置,具体可百度ContentType
还需要注意:如果项目发布在linux上,需注意,windows上的“/”对应linux上的“\”,但是windows上这个不用区别开来,都可以识别路径