简体   繁体   English

如何确保上传的 SVG 有 width 和 height 属性

[英]How to ensure uploaded SVG has width and height Attributes

My users can upload image files, which could be SVGs.我的用户可以上传图像文件,可以是 SVG。

I need to make sure that all SVGs have a width and height attribute for something that's occurring later on.我需要确保所有 SVG 都具有宽度和高度属性,以应对稍后发生的事情。

If I have the SVG as a file (via an input type="file") how can I add a width and height to it if it is missing?如果我有 SVG 作为文件(通过输入类型 =“文件”),如果它丢失,我该如何添加宽度和高度?

I ended up doing the following, though Im sure it could be improved/done in a much better way我最终做了以下事情,尽管我确信它可以以更好的方式改进/完成

 let svgReader = new FileReader();
               
        svgReader.onload = function (e) {
            let svg = $(e.target.result);

            for(let i =0;i<svg.length;i++) {
                if (svg[i] instanceof SVGElement) {
                    svg = $(svg[i]);
                    break;
                }
            }

            let width = svg.attr("width");
            let height = svg.attr("height");
            if (height == null || height == undefined) {
                svg.attr("height", 300);
            }

            if (width == null || width == undefined) {
                svg.attr("height", 300);
            }

            let svgFile = new XMLSerializer().serializeToString(svg[0]);
            let new file = new File([svgFile], files[index].name, {type: "image/svg+xml"});
        };
svgReader.readAsText(files[0]);

I had to go through the SVG to find an instance of SVG element, as some of the SVGs I tested with had additional tags or comments that messed it up otherwise.我不得不 go 通过 SVG 找到 SVG 元素的实例,因为我测试的一些 SVG 有额外的标签或评论弄乱了它。 Also, the 300 value for width and height was just made up, but seems to be ok, probably could have used the view box dimensions instead, but it works for me此外,宽度和高度的 300 值刚刚组成,但似乎没问题,可能可以使用视图框尺寸代替,但它适用于我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM