我正在尝试在客户端下载pdf。 Web API正在创建pdf并将其发送到浏览器响应。
if (!config.pdfXHREnabled) {
$.ajax(
{
url: config.createPDFServiceURL,
data: JSON.stringify(userData),
type: 'POST',
contentType: 'application/json',
dataType: "binary",
processData: false,
success: function (data) {
//AE.tracking.trackEvent('Project', 'PDF generated'); need to be corrected
console.log('PDF generated');
//window.open(data);
// Create a new Blob object using the
//response data of the onload object
var blob = new Blob([data], { type: 'image/pdf' });
//Create a link element, hide it, direct
//it towards the blob, and then 'click' it programatically
var a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
//Create a DOMString representing the blob
//and point the link element towards it
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'My design.pdf';
//programatically click the link to trigger the download
a.click();
//release the reference to the file by revoking the Object URL
window.URL.revokeObjectURL(url);
},
fail: function (err) {
console.error(err);
throw new Error('Failed to create PDF');
}
}
);
}
else {
//this is working solution
var xhr = new XMLHttpRequest();
//set the request type to post and the destination url to '/convert'
xhr.open('POST', config.createPDFServiceURL);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//set the reponse type to blob since that's what we're expecting back
xhr.responseType = 'blob'; //VVIMP
xhr.send(JSON.stringify(userData));
xhr.onload = function (e) {
if (this.status === 200) {
// Create a new Blob object using the response data of the onload object
var blob = new Blob([this.response], { type: 'image/pdf' });
//Create a link element, hide it, direct it towards the blob, and then 'click' it programatically
var a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
//Create a DOMString representing the blob and point the link element towards it
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'My design.pdf';
//programatically click the link to trigger the download
a.click();
//release the reference to the file by revoking the Object URL
window.URL.revokeObjectURL(url);
} else {
console.error('error creating pdf');
throw new Error('Failed to create PDF');
}
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
使用XHR的代码可以正常工作,但是对于ajax来说却失败了。 我不明白我应该在ajax调用中编写什么来获取responseType blob。我尝试在beforeSend中更改xhr。还尝试了xhrFields和堆栈溢出时提供的所有其他解决方案。
我该如何解决?