How to store blob object to mySql database?

Viewed 677

I am generating blob -

let blob = new Blob([document.querySelector("body").outerHTML], {type: 'image/png'});

Output of above code in my case is -
enter image description here

Now from here I want to store the generated blob to MySQL database.
I am using BLOB format in MySQL to store images.
How to store generated blob object to MySQL ?

Edit 1 :
I can see my image at the bottom of the page.

const blobUrl = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = blobUrl;
document.body.appendChild(img);

But I don't know how to store that image as BLOB in MySQL.
Any help or any suggestion ?

Edit 2 :
I am using table structre as -

CREATE TABLE images(
    id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    image_data LONGBLOB,
    image_title CHAR(50),
    size CHAR(50)
);

But what should I pass in image_data ? I just have a Blob object generated by JavaScript.

1 Answers

Just store the data into LONGBLOB type.

Send your image data and image title using AJAX

var data = new FormData();
data.append('title', 'Enter title here');
data.append('image', blob);
$.ajax({
    type: 'POST',
    url: 'upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

Then create table into database

CREATE TABLE images(
    id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    image_data LONGBLOB,
    image_title CHAR(50)
);

Now store your data into variable and insert into created database

upload.php

$image_data = $_POST['image'];
$title = $_POST['title'];

$sql = "INSERT INTO images(image_data,image_title)
        VALUES('$title','file_get_contents($image_data)')";

mysql_query($sql); 
Related