我正在生成一個 Excel 檔案并將其保存到服務器磁盤,現在我需要安全地將這個檔案交付給用戶。下面的代碼status code 200在瀏覽器上實作,但沒有檔案可供下載。
我該怎么做?
public ActionResult GenerateReport(int customer_id)
{
\\file being created
string fileName = "newReport.xlsx";
string filePath = ConfigurationManager.AppSettings["serverSetting"].ToString() "\\Content\\reports\\temp\\" fileName;
excel.SaveAs(new FileInfo(filePath));
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(filePath, contentType, fileName);
}
在前端:
$('#btnGenerateReport').on('click', function () {
$.ajax({
url: '/GeneralReport/GenerateReport',
type: "POST",
contentType: "application/json",
data: JSON.stringify({
customer_id: customer_id
}),
success: function () {
$.Notification.autoHideNotify('success', 'top right', 'Success', 'Success');
},
error: function () {
$.Notification.autoHideNotify('error', 'top right', 'Error', 'Error');
}
});
});
uj5u.com熱心網友回復:
所以,我的案例是一個前端問題:我需要正確獲取可用資訊并進行處理。問題中顯示的后端是正確的。
主要問題是包括xhrFields: { responseType: 'arraybuffer' },在 AJAX 中。
$('#btnGenerateReport').on('click', function () {
$.ajax({
url: '/GeneralReport/GenerateReport',
type: "POST",
contentType: "application/json",
data: JSON.stringify({
customer_id: customer_id
}),
xhrFields: {
responseType: 'arraybuffer'
},
success: function (response, status, xhr) {
var filename = getFileName(xhr);
var blob = new Blob([response]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
$.Notification.autoHideNotify('success', 'top right', 'Success', 'Success');
},
error: function () {
$.Notification.autoHideNotify('error', 'top right', 'Error', 'Error');
}
});
});
function getFileName(xhr) {
var filename = '';
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
return filename;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530147.html
標籤:C#文件下载
