How do I prompt user to save text (xml) to a file?

2019-08-30 04:00发布

I've have some javascript code that transforms XML with XSLT. I now want the user to be able to save that new XML (either by prompting them or throwing the new XML up as a file or something so that the user can then save it. Anybody know how to do that?

var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async = false;
xmldoc.loadXML(responseText); // responseText is xml returned from ajax call
//apply the xslt
var xsldoc = new ActiveXObject("Microsoft.XMLDOM");
xsldoc.async = false;
xsldoc.load("../xslt/ExtraWorkRequest.xslt");
var content = xmldoc.transformNode(xsldoc);

How do I get the user to save the XML (content) as a file?

4条回答
Viruses.
2楼-- · 2019-08-30 04:11

By default, you can't. Browser isn't supposed to access your local disks for security reasons.

But, if you can ask your user to change it's security settings (and you should not to ask), you can to use FileSystemObject or even your Microsoft.XMLDOM.Save method.

查看更多
叼着烟拽天下
3楼-- · 2019-08-30 04:13

You cannot do it with 100% client-side JavaScript with the default security settings. You'll need to implement some server-side logic. In your case, you'll be able to do the XML transformation server-side, as well.

http://www.bigresource.com/Tracker/Track-javascripts-ijfTJlI9/

http://support.microsoft.com/kb/q260519/

查看更多
forever°为你锁心
4楼-- · 2019-08-30 04:17

You could construct a data: URI with a media type of application/octet-stream.

function download (data, charset) {
  if (!charset) {
    charset = document.characterSet;
  }
  location.href = ["data:application/octet-stream;charset=",
                   charset, ",", encodeURIComponent(data)
                  ].join("");
}

All browsers except IE support data: URIs. I think IE8 may support them, but only for images. For IE, a workaround could be to send the data to a server (including document.characterSet) and then load a page that has something like the following header:

Content-Type: application/xml; charset={document.characterSet}
Content-Disposition: attachment

If you want to give the file a name too, use Content-Disposition: attachment; filename=....

Also, for any of this to work, you have to convert your XML to a string first.

查看更多
【Aperson】
5楼-- · 2019-08-30 04:27

I do this with code snippets on my blog (user can click on the save button, and the snippet will come up in their default text editor, where they can tweak it and/or copy it into their app).

It works by putting all the textual data inside of a hidden field, and then submits it to a very simple server-side HTTP handler. The handler just grabs the hidden field value and spits it right back out in the response with the right content-disposition header, giving the user the open/save download prompt.

This is the only way I could get it to work.

查看更多
登录 后发表回答