1

Is it at all possible to download a file upon an ajax request? Does it matter if it's same domain / cross domain?

I know it can be done upon redirecting the browser to a URL and setting relevant headers, but was wondering if it can be done when doing an ajax request.

I'm POSTing JSON as the Request Payload to a URL and based on the content of the JSON, I want to send back a specific file.

client.post(url, body: request, headers:{"Content-Type":"application/json"}).then((res) {
    if (res.statusCode == 200) {
        if ("application/json" == res.headers["content-type"]) {
            // parse JSON here

        } else {
            // download the content if Content-Disposition is set
        }
    }
}).whenComplete(() {
    client.close();
}).catchError((exception, stacktrace) {
    print(exception);
    print(stacktrace);
    showErrorMessage("An Error Occurred");
});

I can see the the correct headers coming back for downloading a PDF, but it's not doing anything if I receive these headers via an AJAX response.

enter image description here

Update - clarifying:

If you click this link, it will do a GET request to Github and download the file: https://github.com/dartsim/dart/archive/master.zip I'm trying to download the file using a POST request via Dart's BrowserClient.post.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Jan Vladimir Mostert
  • 12,380
  • 15
  • 80
  • 137
  • What do you mean by "download a file"? Something like http://blog.butlermatt.me/2014/03/dynamically-generating-download-files/ ? – Günter Zöchbauer Aug 10 '15 at 13:15
  • If you click on a link that points to a file sitting on a server, it will download / open that file depending on what your Content Disposition is set to. If I do window.location to that file, it will also download. Both are GET requests to the server. Now I'm trying to figure out if it's possible to download the file using an AJAX POST - POST JSON to a URL and have the file that's generated server side download in the browser. – Jan Vladimir Mostert Aug 10 '15 at 13:21
  • 1
    Should work with the attempt explained in the above link or something like http://stackoverflow.com/questions/16086162 – Günter Zöchbauer Aug 10 '15 at 13:33
  • Updated the question with an example that should clarify it. – Jan Vladimir Mostert Aug 10 '15 at 13:33
  • 1
    It seems all the solutions in those links uses some sort of GET request whether it's via XHR-GET, window.location to some URL, using iFrames, etc. HTML5's Blob Feature is not supported in the latest IE, so my only option seems to be doing a window.location and passing the params in the JSON as GET paramaters. Not very elegant, but it'll have to do for now. – Jan Vladimir Mostert Aug 10 '15 at 13:41

0 Answers0