【发布时间】: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