简体   繁体   中英

responseType blob works but not new Blob with Ajax

I need to open a pdf based on the content type of an ajax response (using jQuery).

The response type is not known in advance, that's why I have this problem:

This code doesn't work (I get an empty PDF) and it's the one I need to use:

$.ajax("/route").done((data)=>{
    console.log(URL.createObjectURL(new Blob([data], {type: 'application/pdf'})))
})

This code works, my PDF is displayed correctly by clicking on the link. But I don't know the response type in advance so I can't use this code.

$.ajax("/route", {
    xhrFields:{
       responseType: 'blob'
    }
})
.done((data)=>{
    console.log(URL.createObjectURL(data))
})

This problem does not seem to have any other solution than to make sure that the route does return an application/pdf response type. Then we can use the pdf in this way:

let data = api.get('/route', {responseType: "blob"})
let pdfBlob = new Blob([data], { type: "application/pdf" });
let pdfPreview = URL.createObjectURL(pdfBlob);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM