skip to Main Content

I have the image saved in the DB as BLOB datatype

I’m using nodejs with express and I’m using multer library to upload the images

if (req.file) { userProfile.profilePhoto = req.file } await userProfile.save()

this is what I’m doing on the frontend I recieve the profilePhoto as

profilePhoto: { type: "Buffer", data: (15)[string of numbers] }

I tried converting it to a base64 cause I looked other question related to this but didn’t work for me I did it on the client side

import {Buffer} from "buffer" const base64 = Buffer.from( result.data.profilePhoto.data, "binary" ).toString("base64");
which gives me a weird string like this W29iamVjdCBPYmplY3Rd

I want to pass a link to the src attribute I don’t know how to do it any help would be appreciated

also should I handle the conversion in the backend ? what would be the best

2

Answers


  1. Your code

    import {Buffer} from "buffer" 
    const base64 = Buffer.from(result.data.profilePhoto.data,
    "binary" ).toString("base64");
    

    will return a string "W29iamVjdCBPYmplY3Rd".
    Append "data:image/png;base64," prefix to it… and add that to src of your image in the frontend..

    Handling the same can be done in backend also….

    Login or Signup to reply.
  2. NodeJs.

    const fs = require('fs');
    const express = require('express');
    
    const app = express();
    
    app.get('/image', (req, res) => {
       // Read the image buffer from a file or database
       const imageBuffer = fs.readFileSync('path/to/image.jpg');
    
       // Send the image buffer as a response
       res.send(imageBuffer);
     });
    
     app.listen(3000, () => {
       console.log('Server is running on port 3000');
     });
    

    Frontend

    <!DOCTYPE html>
    <html>
    <head>
       <title>Image Display Example</title>
    </head>
    <body>
      <img id="image" alt="Image">
    <script>
     fetch('/image')
      .then(response => response.arrayBuffer())
      .then(buffer => {
        const image = new Blob([buffer], { type: 'image/jpeg' });
        const imageUrl = URL.createObjectURL(image);
        
        // Set the data URL as the image source
        document.getElementById('image').src = imageUrl;
      })
      .catch(error => console.error('Error fetching image:', error));
     </script>
     </body>`enter code here`
     </html>
    

    My opinion: I store all links in backend (somewhere like S3 bucket). And I give only links to front

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search