Reputation: 23
I have images in MySQL. Trying to show one on my React page, so configured Express. Picture in DB stored as mediumblob and encoded in base64. There it looks like
iVBORw0KGgoAAAANSUhEUgAABQAAAAPACAYAAABq3NR5AAAgAElEQVR4AezBCZzXc+I4/uf70zSmTMd0rIqwSWzLLiK5i9....
so I configure Express to get 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 trying to get data at http://localhost:4000/rf i receive not a base64 string, but Unit8Array, it looks 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....
And I can't show it on the page. Help me please, or give me the sample of solving this problem.
Upvotes: 2
Views: 1170
Reputation: 108686
Presumably you want to put an image tag in your web page looking something like this.
<img src="http://localhost:4000/rf" />
and get your /rf endpoint to deliver the image. If that's not the case please edit your question.
To do that, you must deliver the binary image to the browser with the correct MIME type. First decode it from Base64, then set the MIME type, then send it. It's possible code like this will help.
function(err, results, fields) {
if (err) throw err;
if (results && results.length >= 1) { /* results is an array */
const imgdata = Buffer.from(results[0].photo, 'base64')
res.type('png').send(imgdata)
}
Notice that most browsers will accept JPEGs. GIFs, and PNGs as long as they have any one of the valid MIME types (image/png
for example). That is lucky for you, because it doesn't look like you store each image's MIME type in your table.
And, by the way, do your CORS stuff using the npm cors package, not by inserting extra CORS headers in your own code. CORS is a pain in the xxx neck to debug, and the package is already debugged.
Finally, be aware that storing images in databases scales up poorly. You don't want your MySQL server to be the bottleneck if you get tons of traffic. It's best to put your images in a static file system and store their paths in your database.
Upvotes: 1