0

I defined a part of my RESTful API to return a JSON or Excel list of data, based on the Accept in the request. For the JSON version it is easy to use with Ajax (jQuery):

$.ajax({
        url: api.url.measurement,
        contentType: "application/json",
        dataType: "json",
        success: function(result) {
            console.log(result.data);
        }
    });

But, how would I make the browser download the result to a file, when using application/vnd.openxmlformats-officedocument.spreadsheetml.sheet as Accept? I cannot just use a a element, because I have to provide a header.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • The `contentType` should be provided when making a POST or PUT request as it refers to the content type of the body of this POST request. If you have an API that requires a Content-Type request header for a GET request, I would recommend contacting the authors of this REST API and alerting them about this serious design issue within their product. – Darin Dimitrov May 13 '17 at 16:21
  • @DarinDimitrov I wrote the API myself (agreed, this is my first serious try on it, so I am bound to make mistakes). How would I change the API to discern in various types of reply for the same data? – Bart Friederichs May 13 '17 at 16:24
  • Using the `Accept` HTTP request header. This header is sent by the client to indicate to the server under what format he wants the response. For example if you want Excel spreadsheet you use `Accept: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` – Darin Dimitrov May 13 '17 at 16:24
  • @DarinDimitrov OK. In that case, my question is still valid. I'll update my question to no look like a fool ;-). – Bart Friederichs May 13 '17 at 16:25
  • Great, now there are some dupes to your question if you can afford modern browsers that support the HTML5 File API: http://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post/37083012 http://stackoverflow.com/questions/24501358/how-to-set-a-header-for-a-http-get-request-and-trigger-file-download If you need to support legacy browsers your only bet is to add a query string parameter to your GET endpoints allowing to perform the content negotiation and then use an anchor or `window.location=...` – Darin Dimitrov May 13 '17 at 16:33
  • @DarinDimitrov thanks. I am going to go with the query string parameter. The examples I find do not even work in Firefox, and the Firefox docs say the features are experimental: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL – Bart Friederichs May 13 '17 at 16:52

0 Answers0