O
O
oskolade2020-09-22 12:19:37
MySQL
oskolade, 2020-09-22 12:19:37

How to display an image from MySQL in React?

Images are stored in the MySQL database. I'm trying to display an image using React. Set up Express to get data from the database. The image is stored in the database in a mediumblob column. In the database, it is stored in Base64 encoding, looks like

iVBORw0KGgoAAAANSUhEUgAABQAAAAPACAYAAABq3NR5AAAgAElEQVR4AezBCZzXc+I4/uf70zSmTMd0rIqwSWzLLiK5i9....


I configure Express to collect this data:
const mysql = require("mysql");
const bodyParser = require("body-parser");
const express = require("express");
const app = express( );
const port = 4000;
app.use(bodyParser.json( ));

var mysqlConnection = mysql.createConnection({
  host: "host",
  user: "user",
  password: "password",
  database: "db"
});
mysqlConnection.connect((err) => {
  if (!err) {
    console.log("DB Connected");
  }  else  {
      console.log("DB Connection Failed  " + err.message);
  }
});

app.get("/rf", (req, res, next) => {
  mysqlConnection.query(
    "SELECT photo FROM  photo WHERE id=365",
    function(err, results, fields) {
      if (err) throw err;
      res.set("Access-Control-Allow-Origin", "*");
      res.send(results);
    }
  );
});

app.listen(port, ( ) => {
  console.log(`Listening at http://localhost:${port}`);
});


when I try to take a photo, I see that Express gives me not a base64 string, but, as I understand it, a Unit8Array, like:
[{"photo":{"type":"Buffer","data":[105,86,66,79,82,119,48,75,71,103,111,65,65,65,65,78,83,85,104, 69....


Accordingly, I can not display it. Please help me figure it out or give a link to how it should be done.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
oskolade, 2020-09-23
@oskolade

Thanks, I'll study.
Here is a question on Stackowerflow that I found happiness by acting on.

A
Alexander Cheremkhin, 2020-09-22
@Che603000

when I try to take a photo, I see that Express gives me not a base64 string, but, as I understand it, a Unit8Array, like:
[{"photo":{"type":"Buffer","data":[105,86,66, 79,82,119,48,75,71,103,111,65,65,65,65,78,83,85,104,69....

This gives you mysqlConnection.querythe result containing the "photo" property of type Blob
{ phone: Blob}
https://developer.mozilla.org/en/docs/Web/API/Blob
Convert this photo to base64
https://www.geeksforgeeks. org/how-to-convert-blob-...
and send it all to the client.
Don't forget to specify the correct image type in the headers response Content-Type: image/???

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question