如何使用凌空和phpmyadmin更新Android应用中的图片?

时间:2018-10-27 03:32:13

标签: php android image upload android-volley

我正在制作一个Android应用程序。我已经建立了一个带有用户表(user_id,user_name,user_surname,user_image,email,birthdate)的数据库。我已经建立了数据库连接,用户登录,注册。它们可以工作,但是我想通过在android gallery中选择图像来仅更新用户图像。 android代码似乎还可以,但是我认为问题出在.php代码中,因为它不返回任何内容,也不响应任何错误。 android代码显示线程jsonObject = null,response [] 而我的php代码是这个

<?php

require_once '../includes/DbConnect.php';
$errorMsg = array();
$upload_dir = 'images/';

if(isset($_GET['user_id'])){
    $user_id = $_GET['user_id'];
    $sql = "select * from user where user_id=".$user_id;
    $result = mysqli_query($conn, $sql);
    if(mysqli_num_rows($result) > 0){
        $row = mysqli_fetch_assoc($result);
    }else{
        $errorMsg['error'] = true;
        $errorMsg['message'] = 'Could not select a record';
    }
}

if(isset($_POST['btnUpdate'])){
    $user_name = $_POST['user_name'];
    $user_surname = $_POST['user_surname'];
    $email = $_POST['email'];
    $user_password = $_POST['user_password'];
    $birthdate = $_POST['birthdate'];

    $imgName = $_FILES['myfile']['name'];
    $imgTmp = $_FILES['myfile']['tmp_name'];
    $imgSize = $_FILES['myfile']['size'];

    if(empty($user_name)){
        $errorMsg['error'] = true;
        $errorMsg['message'] = 'Please input name';
    }elseif(empty($user_surname)){
        $errorMsg['error'] = true;
        $errorMsg['message'] = 'Please input your last name';
    }elseif(empty($email)){
        $errorMsg['error'] = true;
        $errorMsg['message'] = 'Please input email';
    }elseif(empty($user_password)){
        $errorMsg['error'] = true;
        $errorMsg['message'] = 'Please input password';
    }elseif(empty($birthdate)){
        $errorMsg['error'] = true;
        $errorMsg['message'] = 'Please input birthdate';
    }

    //udate image if user select new image
    if($imgName){
        //get image extension
        $imgExt = strtolower(pathinfo($imgName, PATHINFO_EXTENSION));
        //allow extenstion
        $allowExt  = array('jpeg', 'jpg', 'png', 'gif');
        //random new name for photo
        $userPic = time().'_'.rand(1000,9999).'.'.$imgExt;
        //check a valid image
        if(in_array($imgExt, $allowExt)){
            //check image size less than 5MB
            if($imgSize < 5000000){
                //delete old image
                unlink($upload_dir.$row['user_image']);
                move_uploaded_file($imgTmp ,$upload_dir.$userPic);
            }else{
                $errorMsg['error'] = true;
                $errorMsg['message'] = 'Image too large';
            }
        }else{
            $errorMsg['error'] = true;
            $errorMsg['message'] = 'Please select a valid image';
        }
    }else{
        //if not select new image - use old image name
        $userPic = $row['user_image'];
    }

    //check upload file not error than insert data to database
    if(!isset($errorMsg['message'])){
        $sql = "update user
                                set user_name = '.$user_name.',
                                    user_surname = '.$user_surname.',
                                    email = '.$email',
                                    user_password = '.$user_password',
                                    birthdate = '.$birthdate',
                                    user_image = '.$userPic.'
                where user_id=".$user_id;
        $result = mysqli_query($conn, $sql);
        if($result){
            $errorMsg['error'] = false;
            $errorMsg['message'] = 'New record updated successfully';
            header('refresh:5;index.php');
        }else{
            $errorMsg['error'] = true;
            $errorMsg['message'] = 'Error '.mysqli_error($conn);
        }
    }

}
echo json_encode($errorMsg);

这是android代码

    package com.app.app.bookreview.UserProfile;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.app.app.bookreview.R;
import com.app.app.bookreview.RequestHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

public class PhotoReviewActivity extends AppCompatActivity implements View.OnClickListener{

    private Button uploadPhotoButton, chooseAnotherPhotoButton;
    private CircleImageView profilePhoto;
    private final int IMG_REQUEST = 1;
    private Bitmap bitmap;
    private String UploadUrl = "http://192.168.0.122/book_review/v1/userUpdate.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_review);

        uploadPhotoButton = (Button) findViewById(R.id.upload_photo_button);
        chooseAnotherPhotoButton = (Button) findViewById(R.id.choose_another_photo_button);
        profilePhoto = (CircleImageView) findViewById(R.id.profile_circle);

        uploadPhotoButton.setOnClickListener(this);
        chooseAnotherPhotoButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.choose_another_photo_button:
                selectImage();
                break;

            case R.id.upload_photo_button:
                uploadImage();
                break;
        }
    }

    private void selectImage()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, IMG_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==IMG_REQUEST && resultCode==RESULT_OK && data!=null)
        {
            Uri path = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
                profilePhoto.setImageBitmap(bitmap);
                profilePhoto.setVisibility(View.VISIBLE);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void uploadImage()
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response);
                            String Response = jsonObject.getString("response");
                            Toast.makeText(PhotoReviewActivity.this, Response,Toast.LENGTH_LONG).show();
                            profilePhoto.setImageResource(0);
                            profilePhoto.setVisibility(View.GONE);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("image", imageToString(bitmap));

                return params;
            }
        };

        RequestHandler.getInstance(PhotoReviewActivity.this).addToRequestQueue(stringRequest);
    }

    private String imageToString(Bitmap bitmap)
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
        byte[] imgBytes = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(imgBytes,Base64.DEFAULT);
    }

}

感谢您的帮助

0 个答案:

没有答案