开发者

How do I dynamically create a document for download in Javascript?

开发者 https://www.devze.com 2022-12-23 12:24 出处:网络
I\'m writing some Javascript code that generates an XML document in the client (via Google Earth plugin). I\'d like the user to be able to click a button on the page and be prompted to save that XML t

I'm writing some Javascript code that generates an XML document in the client (via Google Earth plugin). I'd like the user to be able to click a button on the page and be prompted to save that XML to a new file. If I were generating the XML server-side this would be easy, just make the button open the link. But the XML is generated client-side.

I've come up with a couple of hacks that half-work, inspired in part by this StackOverflow question. But neither completely work. Here's a demo HTML with embedded code:

<html><head><script>
function getData() { return '<?xml version="1.0" encoding="UTF-8"?><doc>Hello</doc>'; }
function dlDataURI() {
  window.open("data:text/xml;charset=utf-8," + getData())开发者_JS百科;
}
function dlWindow() {
  var w = window.open();
  w.document.open();
  w.document.write(getData());
  w.document.close();
}
</script><body>
<div onclick="dlDataURI()">Click for Data URL</div>
<div onclick="dlWindow()">Click for Window</div>
</body></html>

The dlDataURI() version works great in Firefox, poorly in Chrome (can't save), and not at all in IE. The Window() version works OK in Firefox and IE, and not well in Chrome (can't save, XML embedded inside HTML). Neither version ever prompts a user download, it always opens a new window trying to display the XML.

Is there a good way to do what I want in client side Javascript? I'd like this to work in today's browsers, ideally Firefox, MSIE 8, and Chrome.

Update with sample Downloadify code

window.onload = function() {
  Downloadify.create("dlify", {
    data: getData(),
    filename: "data.xml",
    swf: 'media/downloadify.swf',
    downloadImage: 'images/download.png',
    width: 100, height: 30});};


The best I've seen as far is Downloadify by Doug Neiner, it requires Flash but works very well:

"A tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction."

Check this video.


If Flash is an option then the Flash Player (version 10+) offers the means for limited reading/writing of files from the local filesystem.

Check this out:

http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/net/FileReference.html#save%28%29

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号