簡體   English   中英

鏈接到SVG生成的下載文件

[英]Link to generated download file from SVG

我想從SVG元素(在我的應用程序界面中為SVG)中創建自定義下載(JavaScript生成的JSON文件)。 但是,盡管我可以使用純HTML(通過強制下載'data:text / plain'URL )來完成此操作,但它不適用於SVG。

一個示例( https://jsfiddle.net/stared/qzn7Ldme/ ):

HTML:

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

JS:

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

如果重要的話,我使用D3.js(3.x)。

有已知的解決方案/解決方案嗎?

您可以簡單地使用實用程序功能來創建行為符合您要求的鏈接。 例如

SVG

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

JS

var content = "This is the file content.";

d3.select("#link_svg").on("click", function () {
  downloadFile("file.txt", content);
});

var downloadFile = function(filename, content) {
  var blob = new Blob([content]);
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  var a = document.createElement("a");
  a.download = filename;
  a.href = URL.createObjectURL(blob);
  a.dispatchEvent(event);
};

我復制了@Fraser的答案,但是使用FileSaver.js可以輕松完成此任務:

 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> </a> </svg> 

您可以通過以下方式更改數據:

data:application/octet-stream

強制下載。 但是download標簽是針對HTML的,而不是針對SVG標記的。 因此,您無法在下載前分配filename.ext。

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

<script>
        var conent = "This is the file content.";
        var header = 'data:application/octet-stream;charset=utf-8,'
        var payload = header + encodeURIComponent(conent);

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

        d3.select("#link_svg").attr("xlink:href", payload)
</script>

需要一個實用程序功能來做到這一點。 看看這里 .-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM