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?

1 answer

  • answered 2022-01-20 07:57 user2445278

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum