How to upload text or images or both to MySQL from android

空扰寡人 提交于 2020-03-16 09:15:56

问题


I try to make a project that upload image to MySQL database..It's work fine when I choose image and upload it. Now I add one edit text tolls..So some times I need to upload only a text, but I can't do that without a picture.

What should I do to get it to upload text, images, or both? And how I can make a default image/ So if user does not select an image,that image default will be becomes default image.

  private static final String HI = "http://10.0.3.2/t/imgupload.php";
    private ImageView img;
    private Button selectImg, uploadImg;
    private Uri filepath;
    Bitmap bitmap;
    final int IMAGE_REQUEST_CODE = 999;
    EditText name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText) findViewById(R.id.name);
        img = (ImageView) findViewById(R.id.imagview);
        selectImg = (Button) findViewById(R.id.select_img);
        uploadImg = (Button) findViewById(R.id.upload_img);
        selectImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityCompat.requestPermissions(MainActivity.this,new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},IMAGE_REQUEST_CODE);
            }
        });
        uploadImg.setOnClickListener(new View.OnClickListener() {
            String img_name = name.getText().toString().trim();
            @Override
            public void onClick(View v) {
                StringRequest stringRequest=new StringRequest(Request.Method.POST, HI, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

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

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> parms=new HashMap<String, String>();
                        String imgdata=imgToString(bitmap);
                        parms.put("imageurl",imgdata);
                        parms.put("name", name.getText().toString().trim());
                        return parms;

                    }
                };
                RequestQueue rq= Volley.newRequestQueue(MainActivity.this);
                rq.add(stringRequest);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode==IMAGE_REQUEST_CODE){
            if (grantResults.length>0&& grantResults[0]== PackageManager.PERMISSION_GRANTED){
                Intent intent=new Intent(new Intent(Intent.ACTION_PICK));
                intent.setType("image/*");

                startActivityForResult(Intent.createChooser(intent,"select image"),IMAGE_REQUEST_CODE);

            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==IMAGE_REQUEST_CODE && resultCode==RESULT_OK && data!=null){
            filepath=data.getData();
            try {
                InputStream inputStream=getContentResolver().openInputStream(filepath);
                bitmap= BitmapFactory.decodeStream(inputStream);
                img.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private String imgToString(Bitmap bitmap){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
        byte[] imgbytes=byteArrayOutputStream.toByteArray();
        String encodeimg= Base64.encodeToString(imgbytes,Base64.DEFAULT);
        return encodeimg;
    }


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:layout_centerHorizontal="true"
        android:id="@+id/imagview"
        android:layout_width="300dp"
        android:layout_height="200dp" />

    <LinearLayout
        android:id="@+id/linearlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imagview"
        android:gravity="center"
        android:orientation="vertical">

        <Button
            android:id="@+id/select_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Select Image" />

        <Button
            android:id="@+id/upload_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="upload image" />

    </LinearLayout>

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="108dp"
        android:layout_marginRight="108dp"
        android:layout_weight="1"
        android:hint="ENter Image Name"
        android:visibility="visible" />


</RelativeLayout>
<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){

 $image = $_POST['imageurl'];
 $name = $_POST['name'];


$user = "root";
$pass = "";
$host= "localhost";
$dbname="db2";
//header('Content-Type: bitmap; charset=utf-8');
$con = mysqli_connect($host,$user,$pass,$dbname);

$sql ="SELECT `id` FROM `uploadimg` ORDER BY id ASC";

$res = mysqli_query($con,$sql);

$id = 0;

 while($row = mysqli_fetch_array($res)){
 $id = $row['id'];
 }

 $p = "uploadimg/$id.jpeg";

 $path = "https://un/h/uploadimage/$p";


 $sqli="INSERT INTO `uploadimg`( `imageurl`,`name`)  values('".$path."','".$name."');";


 if(mysqli_query($con,$sqli)){
 file_put_contents($p,base64_decode($image));
 echo "Successfully Uploaded";
 }

 mysqli_close($con);
 }else{
 echo "Error";
 }

?>

来源:https://stackoverflow.com/questions/60607421/how-to-upload-text-or-images-or-both-to-mysql-from-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!