responseType blob 有效但不适用于 Ajax 的新 Blob

responseType blob works but not new Blob with Ajax

我需要根据 ajax 响应的内容类型(使用 jQuery)打开 pdf。

事先不知道响应类型,这就是我遇到这个问题的原因:

此代码无效(我得到一个空的 PDF),而这是我需要使用的代码:

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

此代码有效,单击 link 即可正确显示我的 PDF。但是我事先不知道响应类型所以我不能使用这个代码。

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

除了确保路由执行 return application/pdf 响应类型之外,这个问题似乎没有任何其他解决方案。那么我们可以这样使用pdf:

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