How to create and upload an XML file on the fly using javascript?

I received the following requirement:

There is a link on the web page. When the user clicks on the link, he must create the file on the fly and a download window will appear. How to do this using java script?

+3
source share
4 answers

If the user trusts you, you can create the XML file directly in your file system. Sample code for Mozilla Firefox:

function mozillaSaveFile(filePath,content)
{
    if(window.Components) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(filePath);
            if(!file.exists())
                file.create(0,0664);
            var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
            out.init(file,0x20|0x02,00004,null);
            out.write(content,content.length);
            out.flush();
            out.close();
            return true;
        } catch(ex) {
            return false;
        }
    }
    return null;
}

if you need support for all browsers, see how it is implemented at http://www.tiddlywiki.com

EDIT: Firefox 17 +, . . : https://bugzilla.mozilla.org/show_bug.cgi?id=546848#c57

+2

, , -:

Script:

function createAndOpenFile(){
    var stupidExample = '<?xml version="1.0" encoding="utf-8"?><aTag>something</aTag>';
    document.open('data:Application/octet-stream,' + encodeURIComponent(stupidExample));
}

, , .

<a href="#" onclick="createAndOpenFile()" download="file.xml">Donwload</a>

Chrome 27 Firefox 21.

: -)

+14

, http://html5-demos.appspot.com/static/a.download.html

javacript

var xmltext = "<sometag><someothertag></someothertag></sometag>";
var pom = document.createElement('a');

var filename = "file.xml";
var pom = document.createElement('a');
var bb = new Blob([xmltext], {type: 'text/plain'});

pom.setAttribute('href', window.URL.createObjectURL(bb));
pom.setAttribute('download', filename);

pom.dataset.downloadurl = ['text/plain', pom.download, pom.href].join(':');
pom.draggable = true; 
pom.classList.add('dragout');

pom.click();
+11

Source: https://habr.com/ru/post/1795246/


All Articles