-1

我是PHPand的初学者Ajax query。我正在尝试上传profile image使用croppie.js plugin. 当我上传时image,图像会像1580192100.png. 但我的问题是不可能retrieve the image根据userid.

这是我尝试过的代码。profilepic.php

<?php

session_start();
require_once "../auth/dbconnection.php";

if (isset($_POST['image'])) {

    $croped_image = $_POST['image'];
    list($type, $croped_image) = explode(';', $croped_image);
    list(, $croped_image)      = explode(',', $croped_image);
    $croped_image = base64_decode($croped_image);
    $image_name = time().'.png';


 // Valid file extensions
 $allowTypes = array( 'bmp', 'jpg', 'png', 'jpeg' , 'JPG');

// if(in_array($fileType, $allowTypes)){

    $stmt = $conn->prepare("UPDATE users SET image = ? WHERE user_id= ?");
    $stmt->bind_param("si", $image_name, $_SESSION['user_id']);
    $stmt->execute();
    if($stmt->affected_rows === 0);


      file_put_contents('blog/'.$image_name, $croped_image);
    echo 'Cropped image uploaded successfully.';




    }else{

        echo "ERROR: Could not prepare query: $stmt. " . mysqli_error($conn);

    }

    $stmt->close();
//    mysqli_stmt_close($stmt);



?>

php fetch代码是;

<?php

require_once 'auth/dbconnection.php';
$sql="SELECT image FROM users WHERE user_id= '".$_SESSION['user_id']."'";
        if($result = mysqli_query($conn, $sql)){
        if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){

$out= '<img src="data:image/png;base64,'.base64_encode($row['image']).'" alt="">';
echo $out;

        }
    }
}
?>

在此处输入图像描述

我不知道我哪里错了。请帮我。

4

1 回答 1

2

看起来该update语句在数据库中设置了图像名称,而不是任何 base64 编码数据(最好只保存名称,否则表会变得很大),因此当您尝试显示图像时,您需要读取图像数据。我修改了上面的使用prepared statement

<?php
    if( !empty( $_SESSION['user_id'] ) ){

        require_once 'auth/dbconnection.php';


        $sql='select `image` from `users` where `user_id`=?';
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param( 's',$_SESSION['user_id'] );

        # determine the correct path for the image
        $filepath=$_SERVER['DOCUMENT_ROOT'] . '/profile/blog/';

        $res=$stmt->execute();
        if( $res ){
            $stmt->store_result();
            $stmt->bind_result($filename);

            while( $stmt->fetch() ){
                /* 
                    You store the filename ( possibly path too ) 
                    so you need to read the file to find it's
                    raw data which you will use as image source.
                    Use the filepath to find the image!!
                */
                printf(
                    '<img src="data:image/png;base64, %s" alt="" />',
                    base64_encode( file_get_contents( $filepath . $filename ) )
                );      
            }
            $stmt->free_result();
            $stmt->close();
            $conn->close();
        }
    }
?>
于 2020-01-28T08:05:41.400 回答