简体   繁体   中英

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

I got a requirement as following:

There is a link on a web page. As user clicks on link it should create a file on the fly and a download box pops up. How to do it using java script?

You can use blobs as shown in this example .

You can have a JavaScript function with the following code:

var xmltext = "<sometag><someothertag></someothertag></sometag>";

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();

After try what Andreas said I will add something:

Script:

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

You have a link like this, note the new download atribute , with it you put the file name.

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

It works at least in Chrome 27 and Firefox 21.

Improved are welcome :-)

You could create a data-URI. Most modern browsers should be able to understand it. See http://en.wikipedia.org/wiki/Data_URI_scheme

If the user trusts you, you can can create XML file directly in his filesystem. Example 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 in http://www.tiddlywiki.com

This doesn't work for because changing privileges was deemed unsafe and removed.这不适用于因为更改权限被视为不安全并已删除。 see here for more details: https://bugzilla.mozilla.org/show_bug.cgi?id=546848#c57

decodeRequest(textToDecode) {

    var decodedString = atob(textToDecode);

    var fileName = "fileName1"+'_RQ';
    var fileType = '.xml';

    var blob = new Blob([decodedString], { type: fileType });

    var a = document.createElement('a');
    a.download = fileName;
    a.href = URL.createObjectURL(blob);
    a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
    a.style.display = "none";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500); 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM