通过android上传图像到mysql数据库

时间:2016-05-09 16:01:31

标签: java php android

你好之前有人说我不应该把它作为blob存储在数据库中,我需要它我有我的理由。上次我问这个唯一的反应就像是不要存储在数据库或其他东西。那么这里是我的代码,其中一部分工作,另一部分不起作用,工作的部分是拍照并在imageview中显示,不工作是上传到mysql数据库。如果需要更多信息,请告诉我我将编辑答案。提前谢谢你。

代码

的活动:

public class takefoto extends BaseNavegationActivity {

Button takebt, sendbt;
String ba1;
String mCurrentPhotoPath;
ImageView mFoto;
int CodServico;

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

    takebt = (Button) findViewById(R.id.takebt);
    mFoto = (ImageView) findViewById(R.id.fotoser);
    takebt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            captureImage();
        }
    });

    sendbt = (Button) findViewById(R.id.sendbt);
    sendbt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            upload();
        }
    });

    Bundle extras = getIntent().getExtras();
    CodServico=extras.getInt("CodServico");
    Log.i("CODSERVICO",CodServico+"");

}

private void upload() {
    Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
    byte[] ba = bao.toByteArray();
    ba1 = Base64.encodeToString(ba,Base64.DEFAULT);

    // Upload image to server
    ServerRequests serverRequests = new ServerRequests(takefoto.this);
    serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() {
        @Override
        public void done(String returnUser) {
            if (returnUser.equalsIgnoreCase("sucesso")) {
                Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show();
            } else{
                showError();
            }
        }
    });

}

private void captureImage() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, 100);
        }
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100 && resultCode == RESULT_OK) {
        setPic();
    }
}

private void setPic() {
    // Get the dimensions of the View
    int targetW = mFoto.getWidth();
    int targetH = mFoto.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    mFoto.setImageBitmap(bitmap);
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);

    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Log.e("Getpath", "Cool" + mCurrentPhotoPath);
    return image;
}

private void showError(){
    android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext());
    dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
    dialogBuilder.setPositiveButton("Ok", null);
    dialogBuilder.show();
}
}

ServerResquest方法:

public  void storeFotoDataInBackground(String ba, int codservico,GetUpdaterCallBack userCallback){
    progressDialog.show();
    new StoreFotoDataAsyncTasck(ba, codservico, userCallback).execute();
}
public class StoreFotoDataAsyncTasck extends AsyncTask<Void, Void, String> {
    String ba;
    int CodServico;
    GetUpdaterCallBack registerCallback;

    public StoreFotoDataAsyncTasck(String ba1, int codservico,GetUpdaterCallBack registerCallback) {
        this.ba = ba1;
        this.CodServico=codservico;
        this.registerCallback = registerCallback;
    }

    @Override
    protected String doInBackground(Void... params) {
        String retorno = null;
        try {

            URL url = new URL(SERVER_ADDRESS + "myphpfile.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("CodServico", this.CodServico+"")
                    .appendQueryParameter("Imagem", this.ba);
            Log.i("IMAGEM",this.ba+" CodServico"+this.CodServico);
            final String postParameters = builder.build().getEncodedQuery();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("POST");
            conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //send the POST out
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(postParameters);
            pw.close();
            conn.connect();
            String result = convertStreamToString(conn.getInputStream());
            JSONObject jObject = new JSONObject(result);
            if(jObject.length()!=0){
                retorno= jObject.getString("estado");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retorno;
    }
}

我的PHP代码:

<?php
$codservic=$_POST['CodServico'];        
$image = $_POST['Imagem'];          
$con = mysqli_connect("xxxxxxxxx","xxxxxxxx","xxxxxxxxx","xxxxxxxxxx") or die('Unable To connect');
$sql = "insert into xxxxxxxx (xxxxxxxx,xxxxxxxx) values(?,?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"is",$codservic,$image);
$sucesso=mysqli_stmt_execute($stmt);
if($sucesso){
    $estado = array();
    $estado[estado] = "sucesso";
    echo json_encode($estado);
}
?>

1 个答案:

答案 0 :(得分:0)

经过大量的搜索后,我得到了最终为那些需要它的人工作,我将发布我的代码。

主要活动:

public class takefoto extends BaseNavegationActivity {

Button takebt, sendbt;
String ba1;
String mCurrentPhotoPath;
ImageView mFoto;
int CodServico;

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

    takebt = (Button) findViewById(R.id.takebt);
    mFoto = (ImageView) findViewById(R.id.fotoser);
    takebt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            captureImage();
        }
    });

    sendbt = (Button) findViewById(R.id.sendbt);
    sendbt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            upload();
        }
    });

    Bundle extras = getIntent().getExtras();
    CodServico=extras.getInt("CodServico");
    Log.i("CODSERVICO",CodServico+"");

}

private void upload() {
    Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
    byte[] ba = bao.toByteArray();
    Log.i("IMAGEM NAO CONVERTIDA",ba+"");
    ba1 = Base64.encodeToString(ba,Base64.DEFAULT);
    // Get image and
    // Upload image to server
    ServerRequests serverRequests = new ServerRequests(takefoto.this);
    serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() {
        @Override
        public void done(String returnUser) {
            if (returnUser.equalsIgnoreCase("sucesso")) {
                Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show();
            } else{
                showError();
            }
        }
    });

}

private void captureImage() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, 100);
        }
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100 && resultCode == RESULT_OK) {
        setPic();
    }
}

private void setPic() {
    // Get the dimensions of the View
    int targetW = mFoto.getWidth();
    int targetH = mFoto.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    mFoto.setImageBitmap(bitmap);
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);

    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Log.e("Getpath", "Cool" + mCurrentPhotoPath);
    return image;
}

private void showError(){
    android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext());
    dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
    dialogBuilder.setPositiveButton("Ok", null);
    dialogBuilder.show();
}
}

服务器请求方法(带数据库的插入部分):

@Override
    protected String doInBackground(Void... params) {
        String retorno = null;
        try {

            URL url = new URL(SERVER_ADDRESS + "yourphpfile.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("Value1", this.CodServico+"")
                    .appendQueryParameter("Image", this.ba);
            Log.i("IMAGEM",""+this.ba);
            final String postParameters = builder.build().getEncodedQuery();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(3000);
            conn.setRequestMethod("POST");
            conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //send the POST out
            PrintWriter pw = new PrintWriter(conn.getOutputStream());
            pw.print(postParameters);
            pw.close();
            conn.connect();
            String result = convertStreamToString(conn.getInputStream());
            JSONObject jObject = new JSONObject(result);
            if(jObject.length()!=0){
                retorno= jObject.getString("status");// if was sucess or not
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retorno;
    }

我的PHP代码:

<?php
$codservic=$_POST['Value1'];    
$image = $_POST['Image'];
header("Content-type: image/jpg");
$img = base64_decode($image);
$con = mysqli_connect("your connection string") or die('Unable To connect');
$sql = "insert into yourtable (yourcamp1,image) values(?,?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"is",$codservic,$img);
$sucesso=mysqli_stmt_execute($stmt);
$estado = array();
if($sucesso){
    $estado[status] = "sucess";
    echo json_encode($estado);
} else {
    $estado[status] = "error";
    echo json_encode($estado);
}
?>