开发者

Download Excel File by sending ajax request

I use a ajaxForm to send in my initial request. The method gets called and all the response is set but when I try to open the window its retriggering a request again. So the request is send twice.Enclosed is my request.

 $('#reportForm').ajaxForm( {

       dataType :'json',
        type :'POST',
        url : 'report/initialRequest.html',

                beforeSubmit :validateSearchField,

                ifModified : true,
                success :function(data, textStatus, jqXHR){},
                complete : function(jqXHR, textStatus) {
                                           window.location.href = "report/initialRequest.html" + "?" +  $('#reportForm').formSerialize();
                            $.unblockUI();
                                           return false;
                 }      
         });     

Is there way that we can stop the second request been sent. the whole purpose of doing this is that generated reports are way too big so when user submits the request jasper reports take long time to get the file so user does not know when exactly the file comes back . So I used a block UI plugin, when the user clicks the submit button the page gets blocked and as soon as the file comes back the I unblock the page.

Or any body has any better ideas on how to achieve this.

Controller Code

@RequestMapping("/report/initialRequest.html")

public  @ResponseBody Map<String, Object> handleInitialRequest
 (HttpSession session, HttpServletRequest request, HttpServletResponse response     ) {


 Collection<Results> results = getResults();

  Map<String,Object> requestMap = new HashMap<String,Object>();         
  try {
getReportDataAsExcel(session, request, response , results );
} catch (JRException e) {
        e.printStackTrace();
}


        requestMap.put("status", "SUCCESS");
        return requestMap;
}



@SuppressWarnings("unchecked")

public void getReportDataAsExcel(HttpSession session,HttpServletRequest request, HttpServletResponse response , Collection results) throws JRException {

    JRDataSource reportSource = new JRBeanCollectionDataSource( results );

    Map parameters = new HashMap();

    JRAbstractLRUVirtualizer virtualizer = null;



//  JRSwapFile swapFile = new JRSwapFile( getServletContext().getRealPath("/reports/"), 1024, 1024);
    JRSwapFile swapFile = new JRSwapFile( getServletContext().getRealPath("/reports/operationalreports/"), 1024, 1024);
    virtualizer = new JRSwapFileVirtualizer(2, swapFile, true);

    parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);    


    //logger.debug(reportUrl);
    Resource mainReport = null;
    JasperDesign design = null;
    JasperReport compiledReport = null;
    JasperPrint outputReport = null;

    try {
       mainReport = getApplicationContext().getResource(reportUrl);

       if (!mainRepo开发者_如何学编程rt.exists()){
         throw new JRRuntimeException("File .jrxml was not found. The file must exists before compiling.");
       }

        InputStream reportInputStream = mainReport.getInputStream();
        design = JRXmlLoader.load(reportInputStream);
        compiledReport = JasperCompileManager.compileReport(design);


       long start = System.currentTimeMillis();
       logger.debug("Starting Time : " +  start);

        outputReport = JasperFillManager.fillReport(compiledReport, parameters, reportSource);

    logger.debug("Filling time : " + (System.currentTimeMillis() - start));
    writeExcel( session, request,  response,outputReport );


    if (virtualizer != null)
    {
        virtualizer.cleanup();
    }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")
public void writeExcel(HttpSession session,HttpServletRequest request, HttpServletResponse response, JasperPrint jasperPrint)  {    


    ByteArrayOutputStream reportOutputStream = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE);

    JRExporter exporter = new JRXlsExporter();

    // Excel specific parameters
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, reportOutputStream);
    try {
        exporter.exportReport();
    } catch (JRException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }


    ServletOutputStream outputStream = null;
    InputStream is = null;
    byte[] res = reportOutputStream.toByteArray();

    try{ 
       response.setContentType(getResponseContentType());
   setResponseHeader(response);

    response.setContentLength(reportOutputStream.size());

       outputStream = response.getOutputStream();
       is = new ByteArrayInputStream(res);

       int iSize = 0;

       byte[] oBuff = new byte[OUTPUT_BYTE_ARRAY_INITIAL_SIZE];

        while ((iSize = is.read(oBuff)) != -1) {
           outputStream.write(oBuff, 0, iSize);

       }



       } catch ( Exception e){
           e.printStackTrace();
       }
      finally {

          try {
            outputStream.flush();
            outputStream.close();  
            response.flushBuffer();


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      }

}


We had a full page request that generates an Excel file. Once the request is done, the display contains a link to the generated Excel file. I changed this process to call the Excel generation page via Ajax, however when the process is completed, it returns the URL to the generated Excel file to the requesting page. The user gets a dialog with the link and they can get the file without running the Excel generation request twice. Could you alter your process to run like that?


You don't need AJAX for that; just use document.location="yourpage.php".

yourpage.php is where you generate the Excel file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜