Home > OS >  file not downloading on ajax post response .net core
file not downloading on ajax post response .net core

Time:05-05

i am facing problem on file response , its not downloading file, please check following code containing controller method and Ajax post call,

the object there is to input an excel file from user on the form, read and calculate the data on conditions and make results accordingly and return the byte array in file response to browser.

everything working smooth, the input file working fine , data reading working fine, just issue there on the response, its not showing any error and pass through all code without error with file not downloading.

[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;
        });

CodePudding user response:

After executing the UploadCallingDocument method, the FileContentResult is returned to the Ajax success function, the download was unsuccessful because you did not operate in success. So I add an action to download, use window.location to redirect to the Download action in controller.

Below code I use serialize an object of type 'System.Byte[]',so I first Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package. Then in ConfigureServices() add a call to AddNewtonsoftJson().

services.AddControllersWithViews().AddNewtonsoftJson();

In your Controller, change your code like below:

        [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");
                    
        }

In your ajax success, change your code like below:

success: function (data) {
                window.location = '/yourcontrollername/Download';
            }

Result: enter image description here

  • Related