使用对Springboot端点的Ajax调用下载pdf

时间:2019-11-27 18:27:31

标签: javascript ajax spring-boot pdf

我制作了一个springboot应用程序,该应用程序在调用特定端点时会返回字节数组(byte[]

@RequestMapping(value="/pdf",method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> generateSesionEntrenamiento(
        @PathVariable String login,
        @RequestParam("date") String date,
        @RequestParam("aim") String aim
        )
        throws UsuarioNotFoundException, SesionEntrenamientoEmptyListException, SesionEntrenamientoInvalidListException, MalformedRequestException, IOException
{

    byte[] contents = pdfService.getPFD(date,aim);


    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);

    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;

}

当我从Postman调用此终结点时,我获得了OK响应,并且可以将请求正文保存为pdf文件。工作正常。可以打开pdf文件,并显示所需内容。

enter image description here

现在,我想使用axaj调用来调用他的端点,如果成功,则打开“另存为”窗口以允许其下载 我已经从here

获得了此功能
    function downloadFile(data, filename, mime) {
    // It is necessary to create a new blob object with mime-type explicitly set
    // otherwise only Chrome works like it should
    const blob = new Blob([data], { type: mime || 'application/octet-stream' });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // IE doesn't allow using a blob object directly as link href.
        // Workaround for "HTML7007: One or more blob URLs were
        // revoked by closing the blob for which they were created.
        // These URLs will no longer resolve as the data backing
        // the URL has been freed."
        window.navigator.msSaveBlob(blob, filename);
        return;
    }
    // Other browsers
    // Create a link pointing to the ObjectURL containing the blob
    const blobURL = window.URL.createObjectURL(blob);
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute('download', filename);
    // Safari thinks _blank anchor are pop ups. We only want to set _blank
    // target if the browser does not support the HTML5 download attribute.
    // This allows you to download files in desktop safari if pop up blocking
    // is enabled.
    if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    setTimeout(() => {
        // For Firefox it is necessary to delay revoking the ObjectURL
        window.URL.revokeObjectURL(blobURL);
    }, 100);
}

ajax通话:

$.ajax({
        url: backEndpoint + "usuarios/" + login + "/sesionEntrenamiento/pdf",
        headers: {
            "Content-Type": "application/pdf"
        },
        method: "GET",
        data: {
            date: "2019-11-28",
            aim: "random aim"
        }
    })
        .done(function (data, textStatus, xhr) {
            downloadFile(data,"pdf_name","application/pdf");
        })
        .fail(function (xhr, textStatus, errorThrown) {
            if (xhr.status == 400 && xhr.responseJSON != null && xhr.responseJSON.description != null) {
                respuestaErrorMensajePersonalizado(xhr.responseJSON.description.substring(0, xhr.responseJSON.description.length - 10));
            } else {
                respuestaError();
            }
        });

这似乎可行,但是当我保存文件时,我只能看到一个黑页: 从js获得的pdf开头,从Postman获得的pdf格式

enter image description here

0 个答案:

没有答案