Piotr Migdal Piotr Migdal - 1 year ago 148
HTML Question

Link to generated download file from SVG

I want to create a custom download (JavaScript-generated JSON file) from an SVG element (in my application interface is in SVG). However, while I can do it for plain HTML (vide Force download of 'data:text/plain' URL) it does not work for SVG.

An example (https://jsfiddle.net/stared/qzn7Ldme/):


<a id="link_html" download="file.txt">download file (from HTML)</a>
<svg height="100" width="300">
<a id="link_svg" download="file.txt">
<text x="0" y="50">download file (from SVG)</text>


var conent = "This is the file content.";
var header = "data:text/plain;charset=utf-8,"
var payload = header + encodeURIComponent(conent);

// works
d3.select("#link_html").on("click", function () {
this.href = payload;

// does not work as intended
d3.select("#link_svg").on("click", function () {
//// line below does nothing:
// this["xlink:href"] = payload;

// opens file in the same window, not as a downloaded file!
d3.select("#link_svg").attr("xlink:href", payload);

If it matters, I use D3.js (3.x).

Is there a know solution / fix?

Answer Source

Using FileSaver.js makes this a easy task:

var content = "This is the file content.";
var blob = new Blob([content]);

d3.select("#link_svg").on("click", function () {
  saveAs(blob, "file.txt");
<script src="https://cdn.rawgit.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script src="https://d3js.org/d3.v3.js"></script>

<svg height="100" width="300">
  <a id="link_svg">
    <text x="0" y="50">download file (from SVG)</text>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download