Saving SVG code to collection

Hey guys,

I need help with a little SVG magic here…

I’m looking for a way of saving SVG code from an uploaded SVG image to a Meteor collection.
The process is:

1 - I choose an SVG image (with an input element)
2 - Somehow I manage to extract this image’s SVG code
3 - I then save this code to a collection.

Any idea how? Ideally I would like to do this without having to save the image itself to an external provider (using Slingshot or something similar).

Thanks!

const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async function(event) {
    const file = event.target.files[0];
    if (file.type === 'image/svg+xml') {
        const code = await file.text();
        MyCollection.insert({ type: 'image/svg+xml', code });
    }
});
1 Like

Thanks for the reply!

It looks like there is no text property inside event.target.files… I am trying to upload an image created on lllustrator. Any idea why?

event.target.files should be a file list, did you check text on event.target.files[0], ie. the file object inside the file list?

I just checked and it works even for non-text file types like a jpeg
I’ve only checked in chrome though, are you testing with another browser?

I checked on event.target.files[0]… (on Chrome)

Okay, it seems that’s a new and experimental API… sorry!

Turns out you can do this with FileReader instead.
I made a little demo to test it out: https://glitch.com/~get-text-from-file

const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async function(event) {
  const file = event.target.files[0];
  const reader = new FileReader()
  reader.onload = function () {
    const code = reader.result;
    console.log(code)
    // insert here etc
  }
  reader.readAsText(file)
});
1 Like

Brilliant!!! It works perfectly. Thank you very much for the help :smiley:

Quick follow-up question: Any idea why every time I load an SVG image saved in my database to the DOM (using Blaze’s triple brackets {{{ }}} ) all other SVG elements on the page simply disappear?

:scream:

No idea, I’ll give it a test

Couldn’t reproduce: GitHub - coagmano/blaze-svg-from-db

But I did notice that the <style> blocks inside each svg applies globally, so the style from one svg can overwrite the styles on the others. Could that be what’s happening?

You could set up webapp to serve the svgs from the database as files, and then use them in img elements or as background-images to sandbox their styles?

Or you could try rendering them as a datauri?

{{#each svg in svgs}}
  <img src="data:image/svg+xml;utf8,{{{svg.code}}}">
{{/each}}

EDIT: I can’t get in-lining to work so :man_shrugging:

1 Like