我从 C# 控制器返回 pdf 字节数组,如下所示:
return new FileContentResult(pdfBytes, "application/pdf") { FileDownloadName = "test.pdf" };.
我的客户端代码如下。我无法从回复中成功下载 pdf 文件。我可以看到它在响应中返回 pdf(通过记录),但我在这里遗漏了一些东西
$.ajax({
type: "POST",
url: config.ExportUrl,
contentType: "application/json",
data: JSON.stringify(params),
success: (response, status, error) => {
this.isExporting = false;
var defaultFileName = "test.pdf";
var blob = new Blob([response]);
var blobUrl = window.URL.createObjectURL(blob);
var anchor = document.createElement('a');
anchor.download = defaultFileName;
anchor.href = blobUrl;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
return response.content;
},
任何帮助将不胜感激。 谢谢 安吉洛
找到了类似的帖子,如下所示,它有效:
var req = new XMLHttpRequest();
req.responseType = "blob";
req.open("POST", config.ExportUrl, true);
req.setRequestHeader('Content-Type', 'application/json');
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
if (typeof window.chrome !== 'undefined') {
// Chrome version
var link = document.createElement('a');
link.href = window.URL.createObjectURL(req.response);
link.download = defaultFileName;
link.click();
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE version
var blob = new Blob([req.response], { type: 'application/pdf' });
window.navigator.msSaveBlob(blob, defaultFileName);
} else {
// Firefox version
var file = new File([req.response], defaultFileName, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
//callback();
}
};
req.send(JSON.stringify(params));