dongzha2525 2016-01-30 05:15
浏览 82
已采纳

如何使用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 (Modified)

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

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

  • 写回答

2条回答 默认 最新

  • doulu1867 2016-01-30 14:01
    关注

    Please refer to my answer to the question:

    Save multiple image into mysql php from android but only one image get inserted

    Edit:

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

    You must make sure the $path value is unique .

    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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作