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

PaulProgrammer
  • 13,123
  • 3
  • 29
  • 49
radlaz
  • 228
  • 2
  • 14

1 Answers1

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> 
PaulProgrammer
  • 13,123
  • 3
  • 29
  • 49
  • 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 – radlaz Jan 15 '19 at 22:10
  • Yep that did it! Thank you! – radlaz Jan 15 '19 at 22:20