Trying to embed an SVG object every which way poss

2019-07-20 17:38发布

问题:

Have tried all the embedding approaches listed on W3 schools and then some more. Explorer will display it improperly sized even when width and height are provided, chrome and firefox just prompt to download. Using Visual Studio 2010 built in development server, likely need to add the mime type for support, don't where to though.

The SVG files are in my content folder and I am creating the html in the view as such, where ImageFileName is "filename.svg":

<object data="/Content/ExternalCats/@RootCat.ImageFileName" type="image/svg+xml"></object>

or

<embed src="/Content/ExternalCats/@RootCat.ImageFileName" width="300" height="100"
type="image/svg+xml"
pluginspage="http://www.adobe.com/svg/viewer/install/" /> 

回答1:

You could try embedding the <svg> directly into the HTML. Modern browsers support it:

@Html.Raw(File.ReadAllText(Server.MapPath("~/content/externalcats/" + RootCat.ImageFileName)))

or serve the SVG with the correct MIME type (image/svg+xml):

public ActionResult Svg()
{
    return File(Server.MapPath("~/content/test.svg"), "image/svg+xml");
}

and then:

<object data="@Url.Action("svg")" type="image/svg+xml">
    <embed src="@Url.Action("svg")" type="image/svg+xml"/>
</object>

or if you are using IIS 7.0+ you could define a static MIME mapping with the .svg extension:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <staticContent>
        <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    </staticContent>
</system.webServer>


回答2:

SVG support has been added to Internet Explorer from IE9. You must be trying with an older version of IE. Have you tried the same page with Firefox and Google Chrome?

Edit:

You could also use this library called SVGWeb. Apparently, this library also enables IE 6, 7 and 8 to render SVG. They have some really nice demos too to try out. The quick-start guide is here.



回答3:

Are you using a local server program (for example a small Python HTTP server) to load your page? If so, you need to make sure it recognizes the MIME-type. Even if the browser supports SVG, if the server doesn't return the correct MIME-type, the browser doesn't know what to do with it and asks you to save.