Kma*_*man 2 javascript asp.net-mvc
是否可以使用 ajax 调用将 FileStreamResult 作为下载文件打开?
控制器方法
public FileStreamResult DownloadPDF()
{
var stream = myHandler.getFileStream("myfile.pdf");
return File(stream, "application/pdf", "myfile.pdf"));
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
在 IE 上运行我被拒绝访问,但在 Chrome 上它运行良好。但是,我确实得到了一个“空白”/无效的 pdf。
XMLHttpRequest()与responseTypeset to一起使用,为元素"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();
});
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用jquery-ajax-blob-arraybuffer.js。另请参阅添加对 $.ajax 上的 responseType 设置为“arraybuffer”的 HTML5 XHR v2 的支持
| 归档时间: |
|
| 查看次数: |
9928 次 |
| 最近记录: |