【问题标题】:Ajax send json to spring boot server and open generated pdf in new tabAjax 将 json 发送到 Spring Boot 服务器并在新选项卡中打开生成的 pdf
【发布时间】:2021-03-05 13:16:43
【问题描述】:

我有一个小型 Web 应用程序,它从表单收集数据,通过 Ajax 将其发送到 Spring Boot 服务器。服务器生成 pdf 文件并将其作为字节数组发送回。然后我希望在新选项卡中打开 PDF,但我在那里看到空 PDF,这是我的问题。 这是 Ajax 方法:

function sendJson(json) {
$.ajax({
    url: "/pdf/create",
    type: "POST",
    data: json,
    contentType: "application/json",
    success: function (data) {
        alert('Success');

        openFile(data)
    },
    error: function (e) {
        console.log('Was trying to send data, but error occurred. ' + json);
        alert('Error sending data to server');
    }
});
}

然后我根据收到的数据创建一个 blob 并打开它。

function openFile(byte) {
    var file = new Blob([byte], {type: "application/pdf"});

    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
}

这是我的 Spring Boot 控制器:

@PostMapping(value = "/pdf/create")
public ResponseEntity<?> preparePdf(@RequestBody String data) throws IOException {
    System.out.println("Data input: " + data);

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> dataObject = mapper.readValue(data, Map.class);

    try {
        return pdfService.createPdfFromTemplate(dataObject);
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.badRequest().body(HttpStatus.BAD_REQUEST);
    }
}

处理在这里:

public ResponseEntity<Resource> createPdfFromTemplate(Map<String, Object> dataObject) throws IOException {

// data saved to DB. PDF is generated and saved locally

    String filename = "generated_file.pdf";

    File pdf = new File(filename);
    byte[] fileBytes = FileUtils.readFileToByteArray(pdf);

    ResponseEntity.BodyBuilder res = ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM);

            return res.body(new ByteArrayResource(fileBytes));
}

生成的 pdf 中的文本是西里尔文,但我不认为问题出在此处,或者某些编码。 我想我在这里遗漏了一些重要的东西。有时我看到不能通过 ajax 或 POST 方法完成的意见不是一个好方法,但发送 json 数据并接收生成的文件似乎是合乎逻辑的。任何想法都表示赞赏。

【问题讨论】:

    标签: javascript java ajax spring-boot pdfbox


    【解决方案1】:

    希望它对某人有用。我在服务器端使用Base64.getEncoder().encodeToString(fileBytes) 将我的字节数组编码为base64 字符串作为我的响应的主体。在打开文件之前在 JS 中,我将其转换为 ArrayBuffer,如下所示:

    function base64ToArrayBuffer(base64) {
        var binaryString = window.atob(base64);
        var binaryLen = binaryString.length;
        var bytes = new Uint8Array(binaryLen);
        for (var i = 0; i < binaryLen; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        return bytes;
    }
    

    文件按我的预期在新选项卡中打开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-22
      • 2019-10-18
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      • 2018-06-19
      相关资源
      最近更新 更多