0

So I have a controller method that creates an excel package and sends the response back to the user to save/download. The problem that I am having is that the response is not prompting the Open/Save dialog from appearing. Is there something I am missing?

 [HttpPost]
 public ActionResult Export()
 {
  var excel = do stuff to create open XML package

  using (var memoryStream = new MemoryStream())
  {
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("content-disposition", "attachment;  filename=" + Convert.ToString(fileName).Replace(" ", "_") + ".xlsx");
     excel.SaveAs(memoryStream);
     memoryStream.WriteTo(Response.OutputStream);
     Response.BinaryWrite(excel.GetAsByteArray());
     Response.Flush();
     Response.End();
    }
   return null
Jack Thor
  • 1,554
  • 4
  • 24
  • 53
  • 1
    When the browser receives an attachment, its behavior is determined by the browser and its settings. For example, Chrome can be set to automatically pick the file name and skip the browser dialog entirely (see [this answer for deets](https://stackoverflow.com/a/16417711/2791540)). It is usually best not to try to usurp the user's preferences. – John Wu Apr 05 '21 at 22:52
  • How are you invoking this action from the browser? Why are you returning null? Have you tried a FileStreamResult? That's kind of an odd content type: maybe you should start with something a little more standard and make small changes until you identify which part of what you're doing is causing problems. – StriplingWarrior Apr 05 '21 at 22:52
  • @StriplingWarrior I am using plain ajax $("#submitExportXSL").on("click", function (event) { $.ajax({ type: 'post', url: '/AssetPortal/Inventory/Export', data:"", success: function (blob, status, xhr) { console.log(blob); console.log(status); console.log(xhr); } }); – Jack Thor Apr 06 '21 at 01:31
  • @JohnWu I checked the browser setting that is not the issue. – Jack Thor Apr 06 '21 at 15:21
  • @JackThor: Well, that explains why the browser isn't showing a save dialog. An ajax request allows you to specify what happens with the data that comes back. All you're doing is logging the blob to the console. If you want to create a file download for it, you have to add the code for that. See, e.g., https://stackoverflow.com/a/29556434/120955, https://stackoverflow.com/a/34587987/120955, https://stackoverflow.com/a/9970672/120955. Alternatively, you could make your click handler create a form on the page and POST it as a full browser load instead of AJAX, and let the browser take over. – StriplingWarrior Apr 06 '21 at 15:25

0 Answers0