I have the following code to download a .csv
file:
$.ajax({
url: urlString,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(data) {
if (data) {
var iframe = $("<iframe/>").attr({
src: data,
style: "visibility:hidden;display:none"
}).appendTo(buttonToDownloadFile);
} else {
alert('Something went wrong');
}
}
});
The urlString
is pointing to a Restful service that generates the .csv
file and returns the file path which is assigned to the src attribute for the iFrame. This works for any .csv
files but I'm having problems with .xml
files.
When I use the same code but changing the contentType
to text/xml
and use it for downloading .xml
files this doesn't work.
Can I use the same approach here for .xml
files?
UPDATE:
Thanks to Ben for pointing me to the right direction. It turns out I don't need the ajax call at all. Instead, I can just use the iFrame and its url attribute to call the web service, which will generate the content, add the header (Content-Disposition
), and return the stream.
You can also offer it as a download from a virtual anchor element, even if the data is client-side:
/*
* Create an anchor to some inline data...
*/
var url = 'data:application/octet-stream,Testing%20one%20two%20three';
var anchor = document.createElement('a');
anchor.setAttribute('href', url);
anchor.setAttribute('download', 'myNote.txt');
/*
* Click the anchor
*/
// Chrome can do anchor.click(), but let's do something that Firefox can handle too
// Create event
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
// Fire event
anchor.dispatchEvent(ev);
http://jsfiddle.net/D572L/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With