Displaying images from a private subdirectory in Meteor

I have a set of images that I store in my subdirectory /private

, I am trying to fetch data inside a server method and send the data back to the client to be displayed.

How can i do this?


I have an image named test.png

inside /private/photos

. Here's what I've tried.

/client/test.js

Template.test.onRendered(function () {
    Meteor.call('returnPhoto', 'photos/test.png', function (e, data) {
        console.log(data);
        console.log(window.btoa(data));
        $('#imgContainerImg').attr('src', 'data:image/png;base64,' + window.btoa(data));
    });
})

      

/server/methods.js

returnPhoto: function (assetPath) {
  return Assets.getText(assetPath);
  return Assets.getBinary(assetPath);
}

      

I tried like Assets.getText

and Assets.getBinary

, the first gives me binary gibberish and the second gives me an array of numbers. Using the function btoa

does not work independently.


I've looked at the CollectionFS package , but I don't need to download the photos and store them all in the collection. I would like the images to be available as soon as I put them in this directory, without being called myFSCollection.insert

.

+3


source to share


2 answers


Using the following, I was able to get images from a private directory, send it to the client as a byte array, which is then converted to base64 string and displayed as a data url.

client /test.js

Template.test.onRendered(function () {
    Meteor.call('returnPhoto', 'photos/test.png', function (e, data) {
        var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(data)));
        $('#imgContainerImg').attr('src', 'data:image/png;base64,' + base64String);
    });
})

      



server /methods.js

returnPhoto: function (assetPath) {
    return Assets.getBinary(assetPath);
}

      

+1


source


This is the solution I'm working with:

client / main.js

const imagesLookup = new ReactiveDict();
Template.registerHelper('img', function(src) {
  Meteor.call('image', src, (err, img)=> {
    imagesLookup.set(src, img);
  });
  return imagesLookup.get(src);
});

      

client / main.html



<template="stuffWithImage">
  <!-- src is the path of the image in private -->
  <img src="{{img src}}"/>
</template>

      

import /methods.js

Meteor.methods({
  image(src){
    //validate input and check if use is allowed to see this asset
    if(Meteor.isClient){
      //return some loading animation
    }
    const buffer = new Buffer(Assets.getBinary(src), 'binary');
    const magicNumber = buffer.toString('hex',0,4)
    const base64String = buffer.toString('base64');
    return `data:image/${getImageType(magicNumber)};base64,${base64String}`;
  }
});

function getImageType(magicNumber){
  if (magicNumber === 'ffd8ffe0') {
    return 'jpeg';
  }
  //check for other formats... here is a table: https://asecuritysite.com/forensics/magic
}

      

+1


source







All Articles