简体   繁体   中英

Android Image Upload to php server base64 not working

I am trying to upload an image from gallery to my local php server with the Base64 method. Code gives no error and everything seems fine, the mysql entry for the record is going through but the image is not saving.

By pressing this button i am getting the image by intent android code

public void uploadImageButtonFunction(View view){

    Intent intent = new Intent();
    // Show only images, no videos or anything else
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    // Always show the chooser (if there are multiple options available)
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

This just opens the gallery for image picking by pressing a button After pressing that button and picking the image here where we receive the image

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            filepathUri = data.getData();

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filepathUri);
                // Log.d(TAG, String.valueOf(bitmap));
                String s = getRealPathFromURI(filepathUri);
                Log.i("imagepath", s);
                textView.setText(s.split("/")[s.split("/").length - 1]);

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

Just assigning to a bitmap we declared in the class variable.

public String getRealPathFromURI(Uri uri) {
    String[] projection = {MediaStore.MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    cursor.moveToFirst();
    String imagePath = cursor.getString(column_index);

    return imagePath;
}

*This method gets the PATH of the image from the uri, the uri is declared globally as class variable*

now this function converts the bitmap to Base64 string

 private String imageToString(Bitmap bitmap){

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

this what uploads it to the php server with POST request with volley library

private void uploadImageBase64(){

StringRequest stringRequest = new StringRequest(Request.Method.POST, signUpUrl,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {


                try {

                    name.setText("");
                    number.setText("");
                    textView.setText("");

                    Log.i("resp", response);
                    Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();

                }catch (Exception e){
                    Toast.makeText(Insert.this, e.getMessage(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }


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

        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

    }
})


{


    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        Map<String, String> params = new HashMap<String, String>();
        params.put("name", name.getText().toString().trim());
        params.put("number", number.getText().toString().trim());
        params.put("image", imageToString(bitmap));

        return params;
    }
};

MySingleton.getInstance(Insert.this).addToRequestQueue(stringRequest);


}

and i copied the MySingleton class from volley documentation

here it is if you need it

package com.example.slimshady.whatsappclone;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    MySingleton(){}

    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(20);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}

now for the php side sim enough code, i am using wamp server

PHP CODE

<?php

$conn=mysqli_connect("localhost","root","", "shady") or die("Unable to connect");

$name = $_POST["name"];
$number = $_POST["number"];
$image = $_POST["image"];

$upload_path = "android_pool/whatsapp/images/$name.jpg"; // String concatination happening here between the $name variable and the .jpg string
$imagelink = "http://1.0.0.2/android_pool/whatsapp/images/$name.jpg";

if(mysqli_connect_error($conn)) {
    echo "Failed To Connect";
}

$qry = "INSERT INTO contacts (`name`, `number`, `imagelink`) VALUES('$name', '$number', '$imagelink')";

$res = mysqli_query($conn, $qry);

if ($res) {


    file_put_contents($upload_path, base64_decode($image));

    echo $image;

    echo json_encode(array('response'=>'image Uploaded'));


}else{
    echo json_encode(array('response'=>'image not uploaded'));
}


mysqli_close($conn);        


?>

records are getting inserted but no images present in the folder Look at the "jojo" record it is inserted but no image uploaded for it 在此处输入图片说明

the images folder does not contain the jojo.jpg 在此处输入图片说明

So what am i doing wrong here ? and is there a better way to achieve what i am trying to do ?

Edit 1:

The Five Images Are Inserted Manually, There Should Be A Jojo.jpg In This Folder Which Is Not Present, But Record Of That Is Present In The Mysql< As Shown In The Image

I solved the issue, it was a peculiar one to be honest. The java code is fine here as expected, the problem was that i didn't knew this weird php behavior,

i was giving the upload path with absolute path, like this

$upload_path = "android_pool/whatsapp/images/$name.jpg"

but php flags this as wrong for some reason, php wants the relative images directory path respect to where the php file i am calling is. i know makes no sense, cause absolute path is always better and why php doesn't work with that i have no clue.

so what works is

$upload_path = "images/$name.jpg"

just by changing this everything works. I solved this by fiddling around and changing things just for the sake of changing. So i felt obligated to answer this unintuitive problem for some poor soul who encounters it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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