Button for downloading SVG in JavaScript & HTML?

做~自己de王妃 提交于 2020-12-10 11:57:34

问题


There's an SVG image that's rendered in the browser. I want a button below to download the SVG. Looks like download with proper mimetype is the way to go.

Attempt:

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

Runnable example: https://stackblitz.com/edit/typescript-mpk8ui

But I get a broken SVG file. Similar issue with my real code (I get an empty SVG).


回答1:


The downloading data must be a blob raw data.

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

This should do the trick.



来源:https://stackoverflow.com/questions/57798877/button-for-downloading-svg-in-javascript-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!