0

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rahul
  • 99
  • 3
  • 8
  • **update:** I checked that the base64 string sent by the front-end and the actual base64 string received by the server for the image are different. The actual base64 string contains `+` symbols but the received string does not. Actual base64 `+kqmzx..` and received base64 `kqmzxt..` – Rahul Apr 01 '20 at 19:44
  • Important: [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Apr 01 '20 at 20:36
  • You have a mistake here: `or die('connection-error')`. You need to remove this. – Dharman Apr 01 '20 at 20:36
  • @Dharman I have removed it and tried but it's still not working. I think the main reason behind this is the incorrect base64 string received by the server. See the 1st comment for more info. – Rahul Apr 02 '20 at 05:47

1 Answers1

0

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";
}
?>
Rahul
  • 99
  • 3
  • 8