简体   繁体   English

Android Image Upload to php server base64无法正常工作

[英]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. 我正在尝试使用Base64方法将图像从画廊上传到我的本地php服务器。 Code gives no error and everything seems fine, the mysql entry for the record is going through but the image is not saving. 代码没有给出错误,一切似乎都很好,记录的mysql条目正在通过中,但是图像未保存。

By pressing this button i am getting the image by intent android code 通过按下此按钮,我通过意图的 Android代码 获取图像

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* *此方法从uri获取图像的PATH ,uri全局声明为类变量*

now this function converts the bitmap to Base64 string 现在,此函数将位图转换为Base64字符串

 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 这是什么与排球库通过POST请求将其上传到php服务器的

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 我从凌空文档中复制了MySingleton类

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端SIM卡足够的代码,我正在使用WAMP服务器

PHP CODE PHP代码

<?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 正在插入记录,但文件夹中没有图像 查看“ jojo”记录,其中已插入但没有图像上传 在此处输入图片说明

the images folder does not contain the jojo.jpg images文件夹不包含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: 编辑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 手动插入了五个图像,该文件夹中应该有一个不存在的Jojo.jpg,但是在Mysql中存在该记录的记录<如图所示

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, Java代码在这里可以正常使用,问题是我不知道这种奇怪的php行为,

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. 但是php由于某些原因将其标记为错误,php希望相对图像目录路径相对于我正在调用的php文件所在的位置。 i know makes no sense, cause absolute path is always better and why php doesn't work with that i have no clue. 我知道这是没有道理的,因为绝对路径总是更好,为什么PHP不起作用,我也不知道。

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. 因此,我不得不为遇到这个问题的一些可怜的灵魂回答这个不直观的问题。

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

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