Reputation: 35059
I'm interfacing a WCS service and have to send HTTP POST requests with XML to the server to retrieve (binary) raster files.
I managed to download the file with a jQuery ajax, but I cannot save the actual file content to the local file system.
Is there any way to achieve this? Preferably I'd like to use the browsers built-in download manager to handle the download.
Upvotes: 2
Views: 4126
Reputation: 9492
Yes, it is possible to save files from Javascript. Basically it generates a blob containing the binary data, then it creates a link to this blob with the HTML5 "download" attribute in order to specify the desired filename, and finally it simulates a click on this link.
// Limited browser support! (latest release versions of Firefox & Chrome are OK)
var DownloadAttributeSupport = 'download' in document.createElement('a');
function showSave(data, name, mimetype) {
var blob, url, builder = new BlobBuilder();
builder.append(data);
if (!mimetype) mimetype = "application/octet-stream";
if (DownloadAttributeSupport) {
blob = builder.getBlob(mimetype);
url = URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href",url);
link.setAttribute("download",name||"Download.bin");
// Now I need to simulate a click on the link.
// IE 10 has the better msSaveBlob method and older IE versions do not support the BlobBuilder interface
// and object URLs, so we don't need the MS way to build an event object here.
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
}
You shoudlk look at https://stackoverflow.com/a/13059556/2227298 for a more complete answer regarding alternative codes for browsers not supporting HTML5 <a download>
Upvotes: 2