在JavaScript&中下载SVG的按钮HTML? [英] Button for downloading SVG in JavaScript & HTML?
本文介绍了在JavaScript&中下载SVG的按钮HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在浏览器中呈现了一个SVG图像.我想要一个按钮来下载SVG.看起来像 下载
正确的模仿类型是解决之道.
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.
尝试:
<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).
But I get a broken SVG file. Similar issue with my real code (I get an empty SVG).
推荐答案
下载数据必须是blob原始数据.
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();
}
这应该可以解决问题.
这篇关于在JavaScript&中下载SVG的按钮HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文