1

Hello I am having issues displaying images uploaded to MySQL. My table looks like so.

  CREATE TABLE IF NOT EXISTS images(id int primary key auto_increment,
  image_id varchar(255) NOT NULL, img LONGBLOB NOT NULL);

I handle the uploaded image on my server like so

 const multer = require('multer');
 const upload = multer({ dest: `static/images/product_images/` });       

 app.post('/upload-image', upload.single('img'), (req, res) => {
  const img = req.file; 

  fs.readFile(img.path, (err, data) => {
   connection.query(`
          INSERT INTO product_images(product_id, img)
                    VALUES(?,?)`,
                    [
                        randomId(),
                        data
                    ],
                    (err, results) => {
                      //etc...
          });
      });
     });

Now if I fetch that image it looks like this

 "img": {
  "type": "Buffer",
  "data": [
    255,
    216,
    255,
    224,
    0,
    16,
    74,
    70,
    etc..
     ]
    }

Am I doing this correctly? When I fetch that image and try to display it on the front end using

 <img src='img-blob'/> 

It doesn't display the image. What am I doing wrong?

I know uploading images to the db is considered a bad idea by some but I have no other choice

1 Answer 1

1

There's a special syntax you should use to have an image inline in the source. I pulled this from the following SO question:

How to display Base64 images in HTML?

<div>
    <p>Taken from wikpedia</p>
    <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
</div> 
Sign up to request clarification or add additional context in comments.

4 Comments

I tried that and I get this error data:image/png;base64, 255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,237,0,108,80,104,111,116,111,115,104 etc... net::ERR_INVALID_URL
Yep that did it! Thank you!
How did you converted this buffer data to base64?
A quick google search yields a link to the documents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.