Kushal
Kushal

Reputation: 3168

Initiate File Download via GET request

So I have ExtJS application in which a certain open in Combo leads to Download of file (read: Export to PDF). Now currently we do that using window.open in which we hit a specific URL which is RESTful in nature and something similar to.

window.open('https://example.com/myapp/api/module/someId/exportPDF.pdf?clientId=bizzare123&param1=someValue');

This opens up new Tab and I get the file to download. Now this is theoretically a GET request (though it doesn't appear in Chrome DevTools' Network tab), and I want to pass some JSON data as request body (data is large so I can't fit it in request params).

Can this be done by calling same URL using Ext.Ajax.request and passing jsonData? (I believe then I'll have to handle file coming in the response within success callback.

Thanks!

P.S. I'm on ExtJS 4.0

Update

Earlier we had only GET request to download the file but to support new feature, we had to customize download by sending POST request first, and API then sent file directly in response to POST request.

But as rixo mentioned in comments that async download of file might not be possible directly, I had to change API such that it sends file URL instead, in POST request, and then I can hit that URL and initiate file download. And given that it's huge enterprise webapp impacting millions of users mostly using IE, I wanted to avoid using modern APIs (which are obviously tempting but not supported on IE, like always).

Upvotes: 1

Views: 7340

Answers (2)

BJ Safdie
BJ Safdie

Reputation: 3419

If you just want the file to download, a common method is to embed an empty, hidden IFRAME in your document, then set the "src" attribute to the URL for the get request.

Here is a decent way of doing just that:

Download File Using Javascript/jQuery

This avoids the whole issue with new tabs or windows opening.

This does not answer your question directly. However, it does address your basic problem, which is how to initiate a less intrusive file download via a "RESTful" URL.

Upvotes: 0

Andrea
Andrea

Reputation: 1057

You want to put a request body in a GET request? This isn't a typical application of the GET protocol (though not explicitly disallowed by the spec), so ExtJS doesn't support it out-of-the-box.

You can see in the ExtJS source code (4.0.7) that parameters to a GET request are automatically appended to the request URI.

if ((method == 'GET' || data) && params) {
  url = Ext.urlAppend(url, params);
  params = null;
}

This answer has more details, but the gist is "Write a proxy that will rewrite the request for you".

Upvotes: 1

Related Questions