簡體   English   中英

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

[英]Android Image Upload to php server base64 not working

我正在嘗試使用Base64方法將圖像從畫廊上傳到我的本地php服務器。 代碼沒有給出錯誤,一切似乎都很好,記錄的mysql條目正在通過中,但是圖像未保存。

通過按下此按鈕,我通過意圖的 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);
}

只需按一個按鈕即可打開圖庫以進行圖像拾取。按下該按鈕並在此處拾取圖像后,我們將在此處接收圖像

@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();
            }
        }
    }

只是分配給我們在類變量中聲明的位圖

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;
}

*此方法從uri獲取圖像的PATH ,uri全局聲明為類變量*

現在,此函數將位圖轉換為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);
    }

這是什么與排球庫通過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);


}

我從凌空文檔中復制了MySingleton類

這是如果您需要它

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;
    }
}

現在為PHP端SIM卡足夠的代碼,我正在使用WAMP服務器

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);        


?>

正在插入記錄,但文件夾中沒有圖像 查看“ jojo”記錄,其中已插入但沒有圖像上傳 在此處輸入圖片說明

images文件夾不包含jojo.jpg 在此處輸入圖片說明

那么,我在這里做錯了什么? 有沒有更好的方法來實現我想要做的事情?

編輯1:

手動插入了五個圖像,該文件夾中應該有一個不存在的Jojo.jpg,但是在Mysql中存在該記錄的記錄<如圖所示

我解決了這個問題,說實話,這是一個獨特的問題。 Java代碼在這里可以正常使用,問題是我不知道這種奇怪的php行為,

我給了絕對路徑的上傳路徑,像這樣

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

但是php由於某些原因將其標記為錯誤,php希望相對圖像目錄路徑相對於我正在調用的php文件所在的位置。 我知道這是沒有道理的,因為絕對路徑總是更好,為什么PHP不起作用,我也不知道。

所以有效的是

$upload_path = "images/$name.jpg"

只是通過更改此選項,一切正常。 我通過擺弄和改變事物來解決這個問題,只是為了改變。 因此,我不得不為遇到這個問題的一些可憐的靈魂回答這個不直觀的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM