I'm trying to upload images from the front-end to my PHP server. I'm converting the image into data:image/jpeg;base64
using FileReader()
in javascript. Here's my js code:
fileSelectHandler = (event) => {
let file = event.target.files[0];
console.log(file);
const reader = new FileReader();
reader.onload = () => {
this.setState({
src: reader.result
});
}
reader.readAsDataURL(file);
}
postImage = () => {
var http = new XMLHttpRequest();
var url = 'http://localhost:9090/assign/uploadimage.php';
var params = 'source=' + this.state.src;
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
}
I inserted the full "image/jpeg;base64,..." string into my MySQL database (in long text type).
$conn = new mysqli("localhost","root","","temp_db") or die('connection-error');
if(isset($_POST['source'])){
$data = $_POST['source'];
$stmt = $conn->prepare("insert into f_data values (?)");
$stmt->bind_param("s",$data);
$done = $stmt->execute();
echo "- inserted -";
$stmt->close();
}
But when I tried displaying the images after retrieving the src-links from the database, the images are either destroyed or not displayed at all. Here's the code:
$conn = new mysqli("localhost","root","","temp_db");
if(!$conn){
die("connection-error-occured");
}
$stmt = $conn->prepare("select * from f_data");
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0){
while($row = $result->fetch_assoc()){ ?>
<img src = "<?php echo $row['src']; ?>" />
<?php
}
}
How should I properly store and retrieve such image-data in PHP?