Skip to content
Advertisement

How to store and retrieve images of type data:image/jpeg;base64?

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?

Advertisement

Answer

Finally Solved! The issue was that the base64 data string received by the PHP server was missing the + symbol. The + symbols were replaced by white spaces. Even the urldecode() in PHP was not reading the + symbol properly.

So by replacing those white spaces by + worked out!

Front-end:

postImage = () => {
        var http = new XMLHttpRequest();
        var url = 'http://localhost:9090/assign/uploadimage.php';
        var params = 'source=' + encodeURI(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);
    }

Back-end:

<?php
//replacing ' ' with '+'
function full_decode($str){
    return str_replace(" ","+",$str);
}

$conn = new mysqli("localhost","root","","temp_db");
if(!$conn){
    die("connection-error");
}

if(isset($_POST['source'])){
    $data = json_decode($_POST["source"],true);
    $data_src = urldecode($data['src']);
    $full_src = full_decode($data_src);
    $stmt = $conn->prepare("INSERT INTO f_data VALUES (?)");
    $stmt->bind_param("s",$full_src);
    $stmt->execute();
    $stmt->close();
    echo "inserted";
}
?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement