前端请求代码:
<script>
$("#btn1").click(function () {
var downloadFile = function () { download("设置文件名称.docx", "DownFile?Id=" + Id); };
downloadFile();
});
function download(fileName, url) {
//要请求的Url和携带的参数
var xhr = new XMLHttpRequest();
//设置响应类型为blob类型
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status === 200) {
// 请求完成
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
var a = document.createElement('a');
a.download = fileName;
a.href = e.target.result;
$("body").append(a); // 修复firefox中无法触发click
a.click();
$(a).remove();
}
}
};
xhr.open("post", url, true);
xhr.send();
}
</script>
后端文件生成代码:
public FileResult DownFile(string Id)
{
byte[] bytes = null;
return File(bytes, "application/octet-stream", "设置文件名称.docx");
}