如何使用 php 和 android 将多张图片上传到服务器(mysql 数据库)

how to upload more than one image to server(mysql database) using php and android

我在我的项目中引用了这段代码..code snippet。 在这里我可以成功上传一张图片..现在我必须上传多张图片..我该怎么做..我对该代码做了一些修改..它只是先保存 image.I 想要要上传的不同图像。这是我改变的..

MainActivity(已修改)

package com.example.test;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button buttonUpload;
    private Button buttonChoose;
    private Button buttonChoose1;

    private EditText editText;
    private ImageView imageView;
    private ImageView imageView1;

    public static final String KEY_IMAGE = "image";
    public static final String KEY_IMAGE1 = "image1";
    public static final String KEY_TEXT = "name";
    public static final String UPLOAD_URL = "http://oursite/PhotoUploadWithText/upload.php";

    private int PICK_IMAGE_REQUEST = 1;
    private int PICK_IMAGE_REQUEST1 = 2;

    private Bitmap bitmap;
    private Bitmap bitmap1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonUpload = (Button) findViewById(R.id.buttonUpload);
        buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
        buttonChoose1 = (Button) findViewById(R.id.buttonChooseImage1);

        editText = (EditText) findViewById(R.id.editText);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageView1 = (ImageView) findViewById(R.id.imageView1);

        buttonChoose.setOnClickListener(this);
        buttonChoose1.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
          private void showFileChooser1() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST1);
        }

   @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) {
        Uri filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
           // imageView1.setImageBitmap(bitmap1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (requestCode == PICK_IMAGE_REQUEST1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //imageView.setImageBitmap(bitmap);
            imageView1.setImageBitmap(bitmap1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

    public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

    public String getStringImage1(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}


    public void uploadImage(){
        final String text = editText.getText().toString().trim();
        final String image = getStringImage(bitmap);
        final String image1 = getStringImage1(bitmap1);
        class UploadImage extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                HashMap<String,String> param = new HashMap<String,String>();
                param.put(KEY_TEXT,text);
                param.put(KEY_IMAGE,image);
                param.put(KEY_IMAGE1,image1);
                String result = rh.sendPostRequest(UPLOAD_URL, param);
                return result;
            }
        }
        UploadImage u = new UploadImage();
        u.execute();
    }


    @Override
    public void onClick(View v) {
        if(v == buttonChoose){
            showFileChooser();
        }
        if(v == buttonUpload){
            uploadImage();
        }
        if(v == buttonChoose1){
            showFileChooser1();
        }
    }
}

upload.php

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

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

    define('HOST','hostname');
    define('USER','username');
    define('PASS','password');
    define('DB','dbname');

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    $sql ="SELECT id FROM uploads ORDER BY id ASC";

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

    $id = uniqid();

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

    $path = "uploads/$id.png";

    $actualpath = "http://oursite/PhotoUploadWithText/$path";

    $sql = "INSERT INTO uploads (image,image1,name) VALUES ('$actualpath','$actualpath','$name')";

    if(mysqli_query($con,$sql)){
        file_put_contents($path,base64_decode($image));
        file_put_contents($path,base64_decode($image1));
        echo "Successfully Uploaded";
    }

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

同一张图片被选择了两次..但只有一份副本保存在我的 uploads 文件夹中 server.Thanks for code @belal khan..

您可以使用 $id = uniqid(); 为图片获取不同的 ID。

在您的 java 代码中,将 private int PICK_IMAGE_REQUEST1 = 1; 更改为 private int PICK_IMAGE_REQUEST1 = 2;

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_IMAGE_REQUEST:
                if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK & null != data) {
                   Uri filePath = data.getData();
    try {
        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        //bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        imageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
                }

                break;

            case PICK_IMAGE_REQUEST1:
                if (requestCode == PICK_IMAGE_REQUEST1 && resultCode == RESULT_OK) {
                    Uri filePath = data.getData();
    try {
        //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        //imageView.setImageBitmap(bitmap);
        imageView1.setImageBitmap(bitmap1);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
    }

问题请参考

编辑:

在您的 PHP 脚本中,您正在覆盖图片上传,因为您对两张图片使用相同的上传路径。

您必须确保 $path 值是唯一的。

试试这个脚本:

<?php

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

    define('HOST','hostname');
    define('USER','username');
    define('PASS','password');
    define('DB','dbname');

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    $path = "uploads/".uniqid().".png";
    $path1 = "uploads/".uniqid().".png";

    $actualpath = "http://oursite/PhotoUploadWithText/$path";
    $actualpath1 = "http://oursite/PhotoUploadWithText/$path1";

    $sql = "INSERT INTO uploads (image,image1,name) VALUES ('$actualpath','$actualpath1','$name')";

    if(mysqli_query($con,$sql)){
        file_put_contents($path,base64_decode($image));
        file_put_contents($path1,base64_decode($image1));
        echo "Successfully Uploaded";
    }

    mysqli_close($con);

}else{
    echo "Error";
}