ошибка синтаксического анализа при вызове jasperreport из ajax в spring mvc

#java #jquery #ajax #spring-mvc #parsing

#java #jquery #ajax #spring-mvc #синтаксический анализ

Вопрос:

Я вызываю конечную точку из jquery ajax для генерации jasperreport с использованием spring mvc, и я хочу просмотреть сгенерированный отчет в формате PDF на новой вкладке браузера. Проблема в том, что я получаю сообщение об ошибке синтаксического анализа с ошибкой преобразования из текста в приложение / pdf, возвращенное в ajax, и если я выполняю отладку запроса из браузера, я вижу текст PDF, полученный в ответ

Вот код Ajax, который вызывает метод spring mvc

 var developerData = {};
        developerData["from"] = $("#productivity_dateTimeFrom").val();
        developerData["to"] = $("#productivity_dateTimeTo").val();
        $.ajax({
            type : "POST",
            contentType : "application/json; charset=utf-8",
            url : 'Productivity',
            data : JSON.stringify(developerData),
            dataType : 'application/pdf',
            success : function(data) {                  
                window.open(data.fileUrl);
            },
            error : function(request,status,error){
                alert(request)
                alert(status)
                alert(error)
            }
        });
  

Метод Spring mvc, вызываемый из ajax:

 @RequestMapping(value = "/Productivity", method = RequestMethod.POST, produces ="application/pdf")
@ResponseBody
public ResponseEntity<byte[]> runReport(@RequestBody String object) throws IOException, JRException {

    db_con db_con = new db_con();
    Resource resource = new ClassPathResource("Productivity.jasper");
    InputStream jasperStream = null;
    Gson g = new Gson();
    try {
        jasperStream = resource.getInputStream();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    DateTimeRange p = g.fromJson(object, DateTimeRange.class);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("p_from_date",dateUtils.convertStringToTimestamp(p.getFrom().replace("T", " ") ":00.000"));
    params.put("p_to_date",dateUtils.convertStringToTimestamp(p.getTo().replace("T", " ") ":00.000"));
    params.put("username", "admin");
    params.put("p2", 1L);
    params.put("p3", "All");
    JasperReport jasperReport = null;

    try {
        jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Connection rep_connection = null;

    try {
        rep_connection = db_con.get_connection();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    JasperPrint jasperPrint = null;
    try {
        jasperPrint = JasperFillManager.fillReport(jasperReport, params, rep_connection);
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    
    try {
        JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_PDF);
    String filename = "report.pdf";

    headers.add("content-disposition", "inline;filename="   filename);

    return new ResponseEntity<>(outStream.toByteArray(), headers, HttpStatus.OK);

}
  

Ответ №1:

Попробуйте загрузить PDF-файл в виде большого двоичного объекта и использовать URL-адрес большого двоичного объекта для его просмотра

     $.ajax({
        type : "POST",
        contentType : "application/json; charset=utf-8",
        url : 'Productivity',
        data : JSON.stringify(developerData),
        xhrFields:{
            responseType: 'blob'
        },
        success : function(data) {                  
            window.open(URL.createObjectURL(data));
        },
        error : function(request,status,error){
            alert(request)
            alert(status)
            alert(error)
        }
    });
  

Комментарии:

1. Что насчет метода контроллера, это правда?