我在檔案回應方面遇到問題,它沒有下載檔案,請檢查以下包含控制器方法和 Ajax 后呼叫的代碼,
那里的物件是在表單上輸入用戶的excel檔案,讀取并計算條件資料并相應地生成結果,并將檔案回應中的位元組陣列回傳給瀏覽器。
一切作業順利,輸入檔案作業正常,資料讀取作業正常,只是在回應中發出,它沒有顯示任何錯誤,并且通過所有代碼沒有錯誤,檔案沒有下載。
[HttpPost]
public async Task<ActionResult> UploadCallingDocument(UploadCallingViewModel model)
{
try
{
FormFileCollection files = Request.Form.Files as FormFileCollection;
{
IFormFile file = files[0];
if (file != null && file.Length > 0)
{
var stream = file.OpenReadStream();
var result = await importExportFileManager.KeepAndShareFileAsync(stream);
return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Summarized_KeepAndShare_File.xlsx");
}
}
}
catch (Exception ex)
{
//to create error notification
}
return RedirectToAction("UploadCalling");
}
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($(this).get(0));
$.ajax({
url: this.action,
type: this.method,
data: formdata,
processData: false,
contentType: false,
beforeSend: function () {
// Doing some loading gif stuff
//displayBusyIndicator();
},
success: function (data) {
console.log('success');
//hideBusyIndicator();
},
complete: function () {
console.log('complete');
//hideBusyIndicator();
}
});
return false;
});
uj5u.com熱心網友回復:
執行UploadCallingDocument方法后,FileContentResult回傳給ajax成功函式,下載失敗是因為你沒有操作成功。所以我添加了一個動作來下載, window.location用來重定向到Download控制器中的動作。
下面的代碼我使用序列化一個'System.Byte []'型別的物件,所以我首先安裝Microsoft.AspNetCore.Mvc.NewtonsoftJsonNuGet包。然后在 ConfigureServices() 中添加對 AddNewtonsoftJson() 的呼叫。
services.AddControllersWithViews().AddNewtonsoftJson();
在您的控制器中,更改您的代碼,如下所示:
[HttpPost]
public async Task<ActionResult> UploadCallingDocument(UploadCallingViewModel model)
{
try
{
FormFileCollection files = Request.Form.Files as FormFileCollection;
{
IFormFile file = files[0];
if (file != null && file.Length > 0)
{
var stream = file.OpenReadStream();
TempData["file"] = await importExportFileManager.KeepAndShareFileAsync(stream);
return Ok();
}
}
}
catch (Exception ex)
{
//to create error notification
}
return RedirectToAction("UploadCalling");
}
[HttpGet]
public virtual ActionResult Download()
{
byte[] data = TempData["file"] as byte[];
return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Summarized_KeepAndShare_File.xlsx");
}
在您的 ajax 成功中,更改您的代碼,如下所示:
success: function (data) {
window.location = '/yourcontrollername/Download';
}
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/472068.html
標籤:阿贾克斯 asp.net 核心 .net-core 文件内容结果
