是否可以使用ajax调用将FileStreamResult打开为下载文件?
控制器方法
public FileStreamResult DownloadPDF()
{
var stream = myHandler.getFileStream("myfile.pdf");
return File(stream, "application/pdf", "myfile.pdf"));
}
Html代码
<a href="#" class="mydownload">Click Me</a>
<script type="text/javascript>
$("a.mydownload").click(function () {
$.ajax({
method: 'GET',
url: 'http://myserver/file/DownloadPDF',
success: function (data, status, jqXHR) {
var blob = new Blob([data], { type: "application/pdf" })
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.click();
}
});
});
</script>
在IE上运行我被拒绝访问,但在Chrome上运行正常。然而,我得到一个“空白”/无效的pdf。
答案 0 :(得分:3)
将XMLHttpRequest()
设置为responseType
时使用"blob"
,将download
属性添加到<a>
元素
$("a.mydownload").click(function () {
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("GET", "http://myserver/file/DownloadPDF");
request.onload = function() {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now()
a.click();
}
request.send();
});
或者,您可以使用jquery-ajax-blob-arraybuffer.js。另请参阅Add support for HTML5 XHR v2 with responseType set to 'arraybuffer' on $.ajax
答案 1 :(得分:1)
仍然存在IE11的问题,但对@ guest271314解决方案的一个小改动,似乎可以解决问题。
$("a.mydownload").click(function() {
var request = new XMLHttpRequest();
request.open("GET", "http://myserver/file/DownloadPDF");
request.responseType = "blob";
request.onload = function() {
var msie = window.navigator.userAgent.indexOf("MSIE");
if (msie > 0) {
window.navigator.msSaveBlob(this.response, "myfile.pdf");
} else {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now()
a.click();
}
}
request.send();
});