Home > Enterprise >  Retrieve image from MYSQL and display it in HTML
Retrieve image from MYSQL and display it in HTML

Time:11-15

I am currently working on an online text editor for writing wikipedia-like articles.
Therefore I have <input type="file" accept="image/*">in HTML.
What I want to do is save the article as text to a MYSQL database and later, when displaying the article take the text from the database to show it in the page. But how would I do this with the Images? What's the best way to save them to a database? And how can I retrieve them from the DB and display them?

I think wikipedia just displays an img-tag with an link to the image as source:
<img src="link_to_image">
but how could I create such a link?

CodePudding user response:

First of all you can store an image in the DB but it's not a good practice. There are already posts about this: Example

What I would do, anyway, is:

  • store the image in a blob column (maybe as base64 string)

First you have to convert the image, then store it in the DB. Assuming you are using PHP, you could do something like this:

$base64 = 'data:image/' . $type . ';base64,' . base64_encode($imageData); 

Then store it in the DB with a simple insert.

  • retrieve the image and return it as a response of a service

In mysql you should just do a select and then return it via (I assume PHP service)

  • browser side, to display the image: Example

This differs from what you want to do

<img src="link_to_image">

I had to do implement a solution similar to this one and works fine enough. You can encounter problems if the image is large in size (2MB for example) or if you want to fetch multiple images at once.

To achieve what you want to do, the best solution is to store the image in a file system that allows you to serve the files or , for example in AWS S3, and just save the image URL in the DB.

  • Related