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

问题描述:

我正在我的项目中引用此代码..代码段. 在这里我可以成功上传一个图像..现在我必须上传多个图像..我该怎么做..我对该代码做了一些修改..它只保存第一个图像.我想要不同的图像上载.这就是我所改变的..

I am referring this code in my project..code snippet. Here i can able to upload one image succesfully..Now i have to upload more than one image..How can i do that one..I did some modification for that code..It is Saving only first image.I want different images to be uploaded. Here is what i have changed..

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 文件夹中只保存了一个副本.感谢@belal khan的代码.

The same image is selected twice..but only one copy is saved in my uploads folder in server.Thanks for code @belal khan..

请参考我的答案:

在PHP片段中,您正在覆盖图像上传,因为您为两个图像使用了相同的上传路径.

In your PHP sript you are overwriting the image upload because you are using the same upload path for both images.

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

You must make sure the $path value is unique .

尝试以下脚本:

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