Ad

Adding An Uploaded File As An Element In An SVG

- 1 answer

If someone uploads an image with a <input type="file"/>, there are a million different ways to add the image somewhere as an <img> element or onto a <canvas>. I want to instead add it as an <image> element in an SVG and I'm totally stymied.

If I add the uploaded file to a canvas and use canvas.getDataURL(), I get a valid data URL that I can use as a background image or whatever. But setting the xlink:href of an <image> element to that URL does nothing. I've also tried adding the file directly without the canvas step, e.g.:

$("#file").on("change",function(){
  $("image").attr("xlink:href",this.files[0]);
});

That seems to do something but still the image won't display. I have a width and height set on it. I've also tried various Blob URL methods and those all don't do anything.

How can I take the image file from a file input and display it as an <image> element in an SVG?

Any assistance much appreciated.

Ad

Answer

The this.files[0] returns a File object. The xlink:href attribute assigment takes string. The automatic conversion of File object to string results in the attribute being assigned the string "[object File]".

You could read the file as a data URL and then assign the data URL to the href attribute. As mentioned in comment by Robert Longson, using JQuery with SVG attribute requiring namespace can sometimes cause problems. I would suggest setting attribute using plain DOM. For example...

var xlinkNS = "http://www.w3.org/1999/xlink";

$("#file").on("change",function(){
    var reader = new FileReader();
    reader.onload = function (e) {
      $("image")[0].setAttributeNS(xlinkNS, "href", e.target.result);
    };
    reader.readAsDataURL(this.files[0])
});
Ad
source: stackoverflow.com
Ad