I am trying to create a service that returns SVG. The requirement is that the SVG has to work in an img tag (script tag would be a bonus) and also to avoid JavaScript.
I have figured that encoding the img in BASE 64 and using it as a URI ,is my best bet.
Java Servlet
String imageString = g2.getSVGElement(); // creates svg html string e.g <svg> blah blah</svg>
byte[] imageData = Base64.encodeBase64(imageString.getBytes());
OutputStream out = response.getOutputStream();
out.write(imageData);
out.flush();
out.close();
Response from GET request
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5v= ...
HTML
<img src="http://localhost:8080/testapp/getSVG?optionone=1&optiontwo=2">
But when I load up the page I get blank img box. I know the base64 img is correct because when I do this . . .
<img src="data:image/svg+xml;base64,PHN22...">
It works fine. How can I implement this with the HTML tag above ?
Why are you returning a data URL from the server? Just return the SVG itself. There is no need for the
data:image/svg+xml;base64,
.You should also make sure you are returning the right MIME type. Ie.:
This lets the browser know that the response is an SVG file.