0

I am currently doing a POST to a Web Api method and am posting an array of objects. When I get to the method, my parameters are resolved properly, and I make a call to the DB and return a list of records.

I then take those records and convert them to a MemoryStream to be downloaded by the browser as an Excel spreasheet. From there, I create an HttpResponseMessage object and set properties so that the browser will recognize this response as a spreadsheet.

public HttpResponseMessage ExportSpreadsheet([FromBody]CustomWrapperClass request){
  var result = new HttpResponseMessage();

  var recordsFromDB = _service.GetRecords(request);

  MemoryStream export = recordsFromDB.ToExcel(); //custom ToExcel() extension method

  result.Content = new StreamContent(export);
  result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  result.Content.Headers.ContentDisposition.Name = "formName";
  result.Content.Headers.ContentDisposition.FileName = "test.xlsx";

  return result;
}

Instead of seeing the spreadsheet being downloaded, nothing seems to happen. When I check the developer tools (for any browser), I see the Response Headers below while the Response tab just shows binary data. Does anyone know what I might be missing here?

enter image description here

gyochum
  • 131
  • 4
  • 12

1 Answers1

0

How are you doing your POST? It sounds like you might be trying to this via a javascript AJAX call, which cannot be done (https://stackoverflow.com/a/9970672/405180). I would instead make this a GET request for starters, and use something like window.location="download.action?para1=value1....". Generally web api Post requests are made to create a file/entry, not retrieve one. Alternatively, you could use a HTML Form with hidden elements corresponding to your query parameters, and use javascript to submit the form.

Community
  • 1
  • 1
Fiddles
  • 2,790
  • 1
  • 32
  • 35
  • When the user clicks the button to export, they are redirected to an angularJs controller method, where i build the object that will posted. I then leverage $http to make the call. Thank you for your reply - I will look into your suggestions. – gyochum May 21 '14 at 13:23