This is a common question asked in various different ways, and I have collected some links below and explain why they don't work. I am looking for a full solution to the following.
In the web application I am developing there is a need for AJAX-esque file downloading with the following requirements
- The user can click the link to download the file and without being directed to a new page, will receive a normal "Save as.." dialog we are all used to in web browsers for downloading files
- If for some reason the server fails to serve up the file, a javascript callback should be called. Similarly, for if the server successfully serves up the file
- Need to be able to modify the HTTP request headers to specify, for example, the Content-Type HTTP header in the request
- Support across all A-grade browsers
Things researched so far:
a. jquery.fileDownload very elegantly solves requirements 1, 2 and 4 by using a combination of form submission, hidden iframes and having the server set a specific cookie. I am very familiar with this project (have contributed to it too). Requirement 3 is not supported though because HTML form submission and iframes (which this library uses) do not allow for specifying HTTP headers to the requested server resource. (jdownloader also uses a similar iframe/form technique, but it also does not solve requirement 3).
b. It is possible to retrieve binary data from a file using XMLHttpRequest (with various hacks for the different browsers (link 1, link 2, link 3, link 4, link 5, link 6, link 7, link 8). But none of them cater for requirement 1. The binary data can be saved in a javascript variable, but there is no way to invoke the browser's "save as..." dialog to allow the user to save this binary data to a file on their hard drive
c. This link (under the "DOWNLOAD + SAVE FILES TO THE HTML5 FILE SYSTEM" heading) has a full end-to-end solution using XHR2 and caters for requirements 1, 2 and 3. But it is badly supported (uses very new HTML5 FileWriter).
Any full solutions out there?
EDIT We have some more options - which I plan to test. Perhaps the only option is to develop a library for this problem by collecting all hacks/solutions together in order to create a universal solution.
According to fibertech's solution below: use solution (b) above to save file into variable and then:
For Internet Explorer: save this data using IE's execCommand()
For others: use data uris (link 2) and the HTML5 download attribute of <a> tag to specify the name (link 1, link 2, link 3, link 4)
This link mentions something to do with using file download ability of canvas
Downloadify (and this link too)
A seemingly relevant link that has to do with web-workers but is doing something with Blob's and the FileApi to generate files.