javascript - How to save image on a Kineticjs canvas to database?
Get the solution ↓↓↓Solution:
You are now writing directly to the server's filesystem, always using 'image.png' as its name (I'm assuming this is a test site and not a production one).
If you wan to save the image contents into the DB, you have to:
- Create a database, using the DB engine you are going to use
- Create a table and add a BLOB type for storing the image's contents. You may also want to get an auto-incrementing ID field, so you can later retrieve the image by using its ID value. The actual table would look like this:
CREATE TABLE image_table( ID INTEGER AUTO_INCREMENT, IMAGE BLOB, PRIMARY KEY (ID)) ENGINE=InnoDB;
- Connect to the DB using the credentials you are going to use
- Execute an INSERT SQL statement, passing the
$_POST['data']
contents as parameter.
$connection = @mysqli_connect('database_hostname','database_username',
'database_password','database_databasename');
mysqli_query($connection ,"INSERT INTO image_table VALUES(NULL, '".
mysqli_real_escape_string($connection , $_POST['data']) ."')");
The call tomysqli_real_escape_string
is necessary to correctly escape the data sent by the JS script, so that it won't cause trouble during the SQL query.
If you want to retrieve the image from the database, you'd have to use aSELECT
type query, such asSELECT ID, IMAGE FROM image_table WHERE ID='".intval(ID)."';"
Once you get the image from the database, you can use something like this to send it to the browser:
//get the data from the database somehow (mysql query et al.)
//let's assume data retrieved from the DB is in $data
header('Content-Type: image/png');//alter for png/gif/etc.
echo $data['IMAGE'];
On the HTML page, you will use it like this
<img src="/myimagescript.php?id=ID">
Answer
Solution:
You don't say which database you're using. Perhaps MySQL since you're using PHP?
Here's one starting example to save your dataUrl string to a MySQL database:
$conn = new PDO('mysql:host=myHost;dbname=myDatabase', "myUser", "myPassword");
// INSERT with named parameters
$stmt = $conn->prepare("INSERT INTO myTable(myImageColumnName)VALUES(:theImage)");
$stmt->bindValue(":theImage",$unencodedData);
$stmt->execute();
$affected_rows = $stmt->rowCount();
echo $affected_rows;
Of course, all examplemy...
must be replaced by your actual database values.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version ">= 7.3.0".
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.