Estoy enfrentando un problema en la respuesta del archivo, no está descargando el archivo, verifique el siguiente código que contiene el método del controlador y la llamada posterior de Ajax,
el objeto allí es ingresar un archivo de Excel del usuario en el formulario, leer y calcular los datos sobre las condiciones y generar resultados en consecuencia y devolver la matriz de bytes en la respuesta del archivo al navegador.
todo funciona sin problemas, el archivo de entrada funciona bien, la lectura de datos funciona bien, solo emita allí en la respuesta, no muestra ningún error y pasa todo el código sin error con el archivo sin descargar.
[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; });Después de ejecutar el método UploadCallingDocument, FileContentResult se devuelve a la función de éxito de Ajax, la descarga no tuvo éxito porque no operó correctamente. Así que agrego una acción para descargar, uso window.location para redirigir a la acción Download en el controlador.
Debajo del código utilizo serializar un objeto de tipo 'System.Byte[]', así que primero instalo el paquete Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet. Luego, en ConfigureServices() agregue una llamada a AddNewtonsoftJson().
services.AddControllersWithViews().AddNewtonsoftJson();En su controlador, cambie su código como se muestra a continuación:
[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"); }En su éxito ajax, cambie su código como se muestra a continuación:
success: function (data) { window.location = '/yourcontrollername/Download'; }