无法从Android上传图片

时间:2019-08-11 21:25:24

标签: php android file bitmap retrofit

我正在尝试注册用户详细信息,例如(姓名,电话号码,电子邮件,密码和图像)。我已经用PHP编写了API,如果我从邮递员发布它,它就可以正常工作。

这是邮递员屏幕截图:
enter image description here

但是当我尝试从android发送数据时,我从服务器收到类似“ Required parameters (name, email or password) is missing!”的错误消息。当我从邮递员发帖而不是从我的android代码发帖时,它正在工作。我肯定做错了。
这是php api:

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Content-Type: application/json');
header('Access-Control-Allow-Headers: Authorization');
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("status" => 1);

if (isset($_POST['name']) && isset($_POST['number']) && isset($_POST['email']) && isset($_POST['password']) && isset( $_FILES[ 'image' ]) && isset($_POST['pns_token']) && isset($_POST['is_owner']) && isset($_POST['tbl_flat_id']) && isset($_POST['tbl_building_id']) && isset($_POST['tbl_society_id'])) {

    $name = $_POST['name'];
    $number = $_POST['number'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
    $pns_token = $_POST['pns_token'];
    $is_owner = $_POST['is_owner'];
    $tbl_flat_id = $_POST['tbl_flat_id'];
    $tbl_building_id = $_POST['tbl_building_id'];
    $tbl_society_id = $_POST['tbl_society_id'];


    //$guest_master = $db -> storeGuest($name, $number, $email, $password, $image);


    // check if user is already existed with the same email
    if ($db->isUserExisted($email)) {
        // user already existed
        $response["status"] = 1;
        $response["message"] = "User already existed with " . $email;
        echo json_encode($response);
    } else {
        // create a new user
        $user = $db->storeUser($name, $number, $email, $password, $image, $pns_token, $is_owner, $tbl_flat_id, $tbl_building_id, $tbl_society_id);
        if ($user) {
             return result
            $response["status"] = 0;
            $response["id"] = intval($user["userId"]);
            $response["message"] = "User registered successfully with " . $email;
            echo json_encode($response);
        } else {
            // user failed to store
            $response["status"] = 2;
            $response["message"] = "Unknown error occurred in registration!";
            echo json_encode($response);
        }
    }
} else {
    // receiving the post params
    $response["status"] = 3;
    $response["message"] = "Required parameters (name, email or password) is missing!";
    echo json_encode($response);
}
?>

这是我的android代码:
NetworkService.java:

public interface NetworkService {
// retrofit get call
@FormUrlEncoded
@POST(Constants.USER_LOGIN)
Call<UserLoginResponse> executeLogin(@Field("email") String email,
                                     @Field("password") String password);

@FormUrlEncoded
@POST(Constants.USER_REGISTER)
Call<UserRegistrationResponse> executeRegistration(@Field("name") String name,
                                                   @Field("number") String number,
                                                   @Field("email") String email,
                                                   @Field("password") String password,
                                                   @Field("image") File imagePath,
                                                   @Field("pns_token") String pnsToken,
                                                   @Field("is_owner") int isOwner,
                                                   @Field("tbl_flat_id") int flatId,
                                                   @Field("tbl_building_id") int buildingId,
                                                   @Field("tbl_society_id") int societyId
                                                   );
}

这是我的RegisterActivity.java。 :

NetworkService networkService = 
App.getClient(EXTENDED_URL).create(NetworkService.class);
Call<UserRegistrationResponse> call = 
networkService.executeRegistration(txtName.getText().toString(),
                            txtNumber.getText().toString(),
                            txtEmail.getText().toString(),
                            txtPassword.getText().toString(),
                            imagePath,
                            pnsToken,
                            0,
                            flatId,
                            buildingId,
                            societyId
                            );

这是在RegsiterActivity中将图像转换为文件的代码:

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        imvPhoto.setImageBitmap(imageBitmap);

        Uri selectedImage = data.getData();

        imagePath = savebitmap("profile_photo", imageBitmap);
    }
}

private File savebitmap(String filename, Bitmap imageBitmap) {
    File filesDir = getFilesDir();
    File imageFile = new File(filesDir, filename + ".jpg");

    OutputStream os;
    try {
        os = new FileOutputStream(imageFile);
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        os.flush();
        os.close();
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
    }
    return imageFile;

}

请提供任何参考或帮助,以便我解决。

1 个答案:

答案 0 :(得分:0)

您必须对此使用多部分。

下面的链接中提供了类似的答案,告诉您如何上传包含其他数据的图像,您可以将其检出。

POST Multipart Form Data using Retrofit 2.0 including image