[英]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”记录,其中已插入但没有图像上传
那么,我在这里做错了什么? 有没有更好的方法来实现我想要做的事情?
编辑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.