11

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?

bstpierre
  • 30,042
  • 15
  • 70
  • 103
Rahul
  • 739
  • 4
  • 15
  • 31
  • 2
    If the file already exists, just create a link to the URL of the file. If that is not the case, I'm pretty sure you have to use server-side code to do this. – Peter Olson Feb 28 '11 at 14:53
  • Creating the XML string is the easy part. Making something synthesized in the browser become a "downloadable" file is hard, if not impossible to do such that it works in all (reasonable) browsers. – Pointy Feb 28 '11 at 14:55

5 Answers5

38

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();
Juan
  • 806
  • 1
  • 8
  • 15
21

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 :-)

Community
  • 1
  • 1
Mikel
  • 5,902
  • 5
  • 34
  • 49
  • 1
    This is a great answer, kudos. It's also not based on non-standard JS like the accepted answer. +1. – Michael Jun 21 '13 at 13:56
3

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

Andreas Gohr
  • 4,617
  • 5
  • 28
  • 45
2

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

EDIT: This doesn't work for Firefox 17+ because changing privileges was deemed unsafe and removed. see here for more details: https://bugzilla.mozilla.org/show_bug.cgi?id=546848#c57

Samuel Chalvet
  • 159
  • 1
  • 13
rmflow
  • 4,445
  • 4
  • 27
  • 41
0
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); 

}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Mar 12 '20 at 14:59