首页 > 解决方案 > php返回的Json对象为空

问题描述

我正在编写一个使用 php 将图像上传到本地服务器的脚本。用户将从 android 应用程序上传图像,我正在使用改造库来这样做。我想在 php 中返回为图像生成的路径和名称,以便在 android 中进行进一步处理。问题是 php 脚本总是返回一个空的 json

PHP 脚本

<?php

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


    $upload_folder = "Signatures"; // Name of the folder.
    $unique_name = microtime().uniqid(); // Name of the image. use time method to make it unique.
    $path = "$upload_folder/$unique_name.jpg";
    $Image = $_POST['image'];


    if (file_put_contents($path,base64_decode($Image)) != false) {


        $data = [ 'imagePath' => $path];
        header('Content-type: application/json');
        echo json_encode( $data );
        exit;   
        } 

    else {
        $data = [ 'imagePath' => 'No image path'];
        header('Content-type: application/json');
        echo json_encode( $data );
        exit; 
        }   
    }

else {

    $data = [ 'imagePath' => 'No image path'];
        header('Content-type: application/json');
        echo json_encode( $data );
        exit;

}

?>

Retorift 方法签名

    @FormUrlEncoded
@POST ("Images.php")
Call<JSONObject> uploadImage (@Field("image") String image );

上传图片方法

 public void uploadImage(){

    String image =  imageToString(signatureView.getSignatureBitmap());

    IAPI iAPI = Application.getImage();
    Call<JSONObject> call = iAPI.uploadImage(image);

    call.enqueue(new Callback<JSONObject>() {
        @Override
        public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {

            if (response.isSuccessful()) {
                Log.d("test" , "is succ");

                try {

                    JSONObject responseJSON = response.body();
                    Log.d("test" , responseJSON.toString());
                    String path = responseJSON.getString("path");
                    if (path == null) {
                        Log.d("test" , "path is null");
                    } else {
                        Log.d("test" , "path not null");
                    }
                } catch (JSONException e) {
                    Log.d("test" , e.toString());
                    e.printStackTrace();
                }

            } else {
                Log.d("test" , "not  succ");
            }
        }

        @Override
        public void onFailure(Call<JSONObject> call, Throwable t) {
            Log.d("test", " in onFailure  - load image :" + t.getMessage() + t.toString());
        }
    });




}

它总是抛出一个异常,说路径没有价值。并且日志中的 responseJSON.toString() 打印空 []。

编辑 :

我创建了自己的模型,其中包含名为 imagePath 的属性,现在它正在工作。谢谢你们

标签: javaphpandroidretrofit

解决方案


推荐阅读