【问题标题】:Button for downloading SVG in JavaScript & HTML?用于在 JavaScript 和 HTML 中下载 SVG 的按钮?
【发布时间】:2019-09-05 05:21:58
【问题描述】:

在浏览器中呈现了一个 SVG 图像。我想要下面的按钮来下载 SVG。看起来 download 具有正确的 mimetype 是要走的路。

尝试:

<div id="container"></div>
<button id="download">Download SVG</button>
function downloadSVG() {
    const svg = document.getElementById('container').innerHTML;
    /*console.info(btoa(svg));

    document.getElementById('svg').src = `data:image/svg+xml;utf8,${document.createTextNode(svg).textContent}`;
    console.info('src:', document.getElementById('svg').src, ';');*/

    const element = document.createElement('a');
    const mimeType = 'image/svg+xml'; // 'image/svg+xml;utf8';
    element.href = `${mimeType},${document.createTextNode(svg).textContent}`;
    element.target = '_blank';
    element.mimeType = mimeType;
    element.download = 'w3c.svg';
    element.id = 'downloader';
    document.body.appendChild(element);
    element.click();
    document.getElementById('downloader').remove();
}

可运行示例:https://stackblitz.com/edit/typescript-mpk8ui

但是我得到了一个损坏的 SVG 文件。与我的真实代码类似的问题(我得到一个空的 SVG)。

【问题讨论】:

    标签: javascript html svg download anchor


    【解决方案1】:

    下载数据必须是 blob 原始数据。

    function downloadSVG() {
      const svg = document.getElementById('container').innerHTML;
      const blob = new Blob([svg.toString()]);
      const element = document.createElement("a");
      element.download = "w3c.svg";
      element.href = window.URL.createObjectURL(blob);
      element.click();
      element.remove();
    }
    

    这应该可以解决问题。

    【讨论】:

    • 谢谢! - 现在只是用我的真实 SVG 图像调试这个 This XML file does not appear to have any style information associated with it. The document tree is shown below. 错误:\
    • 想通了! - 需要getElementsByTagName('svg')[0].setAttribute('xmlns', 'http://www.w3.org/2000/svg'):\
    • 我也有同样的问题,但不能用@AT解决方案解决。我们可以给我完整的代码吗?谢谢
    • 您需要 OUTERHTML..const svg = document.getElementById('container').outerHTML; 才能正常工作并摆脱 此 XML 文件似乎没有任何与之关联的样式信息。文档树如下所示。
    • 谢谢@tomhermans。 @suish 你能做出改变吗?
    猜你喜欢
    • 1970-01-01
    • 2022-06-28
    • 2017-08-18
    • 1970-01-01
    • 2013-07-02
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多