radlaz
radlaz

Reputation: 318

node.js - Upload image to MySQL table

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

Upvotes: 1

Views: 4364

Answers (1)

PaulProgrammer
PaulProgrammer

Reputation: 17630

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> 

Upvotes: 1

Related Questions