简体   繁体   English

使用php将android中的base64图像上传到服务器时出错

[英]errro in Uploading base64 image from android to server using php

I am uploading an image from phone gallery to my database . 我正在将图像从手机库上传到数据库。 I am posting the base64 string of the image to server .Here is my php code. 我将图像的base64字符串发布到服务器。这是我的php代码。

    <?php 

 define('DB_HOST', 'localhost');
 define('DB_USER', 'root');
 define('DB_PASS', '');
 define('DB_NAME', 'sample_userdata');

 //connecting to database and getting the connection object
 $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if($conn)
{
    $image=$_POST["image"];
    $uploadpath="uploads/profilepic.jpg";
    if(isset($image)){
        if(file_put_contents($uploadpath,base64_decode($image))){
        echo json_encode(array('response'=>'Image Uploaded successfully'));}

    }else{
        echo json_encode(array('response'=>'Image upload failed'));
    }
}else{

echo json_encode(array('response'=>'Image upload failed 2'));}
mysqli_close($conn);
?>

The image is getting saved in the uploads folder successfully and android logcat is showing the response 图片已成功保存到uploads文件夹中,并且android logcat显示了响应

D/Response: {"response":"Image Uploaded successfully"} D /响应:{“响应”:“图像成功上传”}

But the localhost/profilepic.php which contains the code is showing Notice: 但是包含代码的localhost / profilepic.php显示了注意:

Undefined index: image in C:\\xampp\\htdocs\\profilepic.php on line 13 {"response":"Image upload failed"} 未定义的索引:第13行上的C:\\ xampp \\ htdocs \\ profilepic.php中的图像{“响应”:“图像上传失败”}

what is the problem , the image is successfully stored in uploads folder , android is giving success message but the localhost page is giving error. 问题是什么,图像已成功存储在uploads文件夹中,android给出了成功消息,但localhost页面给出了错误。

While hitting URL from browser localhost/profilepic.php is GET method. 从浏览器localhost/profilepic.php URL时,是GET方法。 The code is excepting image via POST request. 该代码是通过POST请求排除的图像。

You can add check to validate the request to avoid this warning message. 您可以添加检查以验证请求,以避免出现此警告消息。

Add following code at top of your file to check image is sent or not with request 在文件顶部添加以下代码以检查图像是否根据请求发送

if( !isset($_POST["image"]) || empty($_POST["image"])
{
    echo json_encode(array('response'=>'Image is required'));
    exit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM