简体   繁体   English

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

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

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

The same image is selected twice..but only one copy is saved in my uploads folder in server.Thanks for code @belal khan.. 选择同一张图片两次。.但是在服务器的我的上载文件夹中只保存了一个副本。感谢代码@belal khan ..

You can use $id = uniqid(); 您可以使用$id = uniqid(); in order to get different id for the images. 为了获得不同的图像ID。

In your java code, change private int PICK_IMAGE_REQUEST1 = 1; 在您的Java代码中,将private int PICK_IMAGE_REQUEST1 = 1;更改为private int PICK_IMAGE_REQUEST1 = 1; to private int PICK_IMAGE_REQUEST1 = 2; 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();
    }
}
    }

Please refer to my answer to the question: 请参考对问题的回答:

Save multiple image into mysql php from android but only one image get inserted 从Android将多个图像保存到mysql php中,但仅插入一个图像

Edit: 编辑:

In your PHP sript you are overwriting the image upload because you are using the same upload path for both images. 在PHP片段中,您正在覆盖图像上传,因为您对两个图像使用了相同的上传路径。

You must make sure the $path value is unique . 您必须确保$path值是唯一的。

Try this script: 试试这个脚本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM