简体   繁体   中英

How to ensure uploaded SVG has width and height Attributes

My users can upload image files, which could be SVGs.

I need to make sure that all SVGs have a width and height attribute for something that's occurring later on.

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?

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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