我正在使用 jQuery 和文件标签上传 svg:
HTML:
<input type='file' />
<img id="myImg" src="#" alt="your image" />
jQuery:
$(function () {
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
SVG 上传正常并显示在图像标签上。问题是,我需要将 svg 嵌入到 html 中,而不仅仅是将其显示为图像。知道如何获取 svg 代码并将其嵌入到 html 中吗?
最佳答案
我想推荐给你 the docs
它说你会得到一个带有数据属性的 base64 编码字符串。因此,为了获得明文,您需要删除“data:*/*;base64”(在您的情况下可能是 */* 的 image/svg+xml,但您可以在开发工具中查找)开始然后进行 base64 解码。之后,您应该能够将 svg 直接放入 dom 中。
解码:
let base64 = e.target.result.split('base64,')[1];
let clear = atob(base64);
关于javascript - 使用 jQuery 嵌入上传的 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50385435/