无法使用Servlet和Ajax生成pdf

时间:2017-10-08 05:41:41

标签: java jquery ajax servlets

我的方案是下载PDF文件。我根据成功或失败情况发送两种类型的响应。我无法从Ajax生成报告。我该如何解决?

服务器端

public void generatePdf(HttpServletRequest request, HttpServletResponse response,@PathVariable("dealId") String dealId) throws <Exceptions>{

try {
    byte[] documentBytes = // Some bytes
    response.setHeader("Content-Disposition", "inline;filename=Sample.pdf");
    response.setContentType("application/pdf");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, postcheck=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(documentBytes.length); 
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();       
        out.write(documentBytes);
        out.flush();
        out.close();
    } catch (IOException e) {
        logger.error(e);
    }
} catch(Exception e) {
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    String msg = "Exception occured in pdf generation"; --> I want to catch this message in Ajax response
    out.write(msg.getBytes());
    out.flush();
    out.close();
}
}

的Ajax

$.ajax({
          url: url,           
          cache: false,          
          timeout: 20000,
          success: function(response, status, xhr){ 
                var ct = xhr.getResponseHeader("content-type") || "";
                if (ct.indexOf('html') > -1) {
                    console.log("11");
                  //do something
                }                    
              },
 }

P.S:我不想使用window.open因为我想要捕获异常,如果失败的话。

0 个答案:

没有答案