Search code examples
javascriptnode.jsmongodbejsmulter

How to get image's src attribute from MongoDB to external JavaScript


I'm trying to change the img's src attribute through external javascript but I couldn't find a way to do so...

Best I can do is passing through the data-attribute but since it's stringified it won't work. The goal is getting their full path from external javascript. Can I make this happen?

<body
... 

<div class='test' data-test-value='<%= JSON.stringify(image) %>'></div>

<script src="/js/external.js"></script>
</body>
// external.js
let source = $('.test').attr('data-test-value')
let src = `data:image/${source.image.contentType};base64, ${source.image.data.toString('base64')}>`

Solution

  • You could pass it to JavaScript as an object and store it in a global variable, and then convert typed array to base64 string and assign it to src attribute.

    // global variable
    const source = <%- JSON.stringify(image); %> 
    
    // external.js
    // note: need to turn typed array to base64 string with JS
    
    console.log('JSON image global: ', source);
    
    let src = `data:image/${source.image.contentType};base64, ${btoa(String.fromCharCode(...new Uint8Array(source.image.data)))}`;
    

    And if you only need base64 string, and want to avoid conversion on the client, you could simply convert image to base64 on the server, and also pass it to JavaScript as a global variable:

    // alternatively, you could convert image to base64 right on the server
    const base64Image = '<%= source.image.toString('base64') %>';
    

    edit

    the image variable must be declared as a global variable in the template before external.js is loaded:

    <script>
        // global variable, not within functions/methods etc.
        const source = <%- JSON.stringify(image); %> 
    
         $(document).ready(function(){
            //...
         });
    
    </script>
    
    <script src="/js/external.js"></script>