Java – set byte [] to download as a file

I have a jasper report that generates an excel file and outputs it as byte []. I want the file to be displayed as a download in the browser, but at the moment it just prints the original code to the browser

The relevant part of the code is as follows, which is started from the Ajax request (the page has been loaded):

JasperReport jasperReport;
    JasperPrint jasperPrint;
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();    

    byte[] excel = null;
    FacesContext facesContext = FacesContext.getCurrentInstance();

    try {
        ArrayList<SwimDataReport> dataList = getData();
        if(dataList!=null){
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(dataList,false);

            jasperReport = JasperCompileManager.compileReport(reportFile.getPath());
            jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,dataSource);
            JRXlsExporter exporter = new JRXlsExporter();
            ByteArrayOutputStream  xlsReport = new ByteArrayOutputStream();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,xlsReport);            
            exporter.exportReport();
            excel = xlsReport.toByteArray();

            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition","attachment; filename=\"Export.xls\"");

            xlsReport.close();

            OutputStream  ouputStream = response.getOutputStream();
            ouputStream.write(excel);
            ouputStream.close();

            facesContext.responseComplete();
            this.cleanUp();
        }else{
            return;
        }
    } catch (JRException e) {       
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

Any idea I made a mistake?

Solution

It seems that you can't request to download files from Ajax, so I used H: CommandButton to trigger the download

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>