0

I am working on c# and using the library to create an excel file, but it seems not to work properly. The task is very simple. I use a button which excutes an ajax call to connect to this function in the backend. However, even though it returns "success" I dont see any file locally downloaded.

Is there something I'm missing out?

AJAX Call

$.ajax({
    url: 'WebService.asmx/downloadExcel',
    type: 'POST',
    data: { _result: $json },
    success: function (response) {
        console.log("success to download");
    },
    error: function (error) {
        console.log("failed to download");
        console.log(error);
    }
});

WebService.cs - downloadExcel()

HttpContext.Current.Response.ClearContent();      
HttpContext.Current.Response.BufferOutput = true; 
HttpContext.Current.Response.BinaryWrite(package.GetAsByteArray());
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=@C:/ExportData.xlsx");
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.Flush(); 
HttpContext.Current.Response.End();  
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Hclee
  • 43
  • 2
  • 8
  • The POST is your problem. Downloading is GET. But there are workarounds. Look around here: https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post – ZorgoZ Dec 06 '18 at 21:14
  • @ZorgoZ but I have a lot of data to send over, if i use get method it doesnt allow me to send it over – Hclee Dec 06 '18 at 21:19
  • Then you need to check the workarounds. But the query can be quite long, and you could mime encode any jsonized object as get parameter. Do you need to send that much data? – ZorgoZ Dec 06 '18 at 21:23
  • @ZorgoZ Ok, I will check the workarounds, and yes. I am sending an object array data to fill out an excel file, so it is quite big – Hclee Dec 06 '18 at 21:25
  • You problem is, that even if you get the content, the local file save dialog is not triggered with post. Actually even ajax itself might not trigger it. This look cleaner, but it is actually the same workaround approach: https://nehalist.io/downloading-files-from-post-requests/ – ZorgoZ Dec 06 '18 at 21:28
  • @ZorgoZ I will try and thx – Hclee Dec 06 '18 at 21:30

0 Answers0