前端請求代碼:
<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");
}