使用 android 和 php 将图像上传到服务器(mysql 数据库)
Uploading image to server(mysql database) using android and php
在我的代码中,我有两个图像和两个 edittext 字段要发送到数据库,使用 php file.Here 在我的代码中,我可以插入 2 个图像和 edittext 字段,而无需任何问题。
现在我的问题是,当用户输入两个编辑文本字段并且 select 只插入一张图像时,它会抛出 NullPointerException
。使用此代码,我必须强制性地 select 2 张图像。 .我怎样才能让那个成为可选的?我的意思是用户可以 select one/two 基于他的 requirement.But 的图像,如果我 select 只有一个图像,它会抛出空指针 exception.please 帮帮我..!!
MainActivity.java
package com.example.test;
import android.app.Activity;
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 Activity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
private Button buttonChoose1;
private EditText edithouse;
private EditText editbuild;
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 = "house";
public static final String KEY_TEXT1 = "build";
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.save);
buttonChoose = (Button) findViewById(R.id.choose);
buttonChoose1 = (Button) findViewById(R.id.choose1);
edithouse = (EditText) findViewById(R.id.houseno);
editbuild = (EditText) findViewById(R.id.buildno);
imageView = (ImageView) findViewById(R.id.imageViews);
imageView1 = (ImageView) findViewById(R.id.imageViews1);
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 house = edithouse.getText().toString().trim();
final String build = editbuild.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,house);
param.put(KEY_TEXT1,build);
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
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$house = $_POST['house '];
$image1 = $_POST['image1'];
$build = $_POST['build '];
require_once('dbConnect.php');
$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/".uniqid().".png";
$path1 = "uploads/".uniqid().".png";
$actualpath = "$path";
$actualpath1 = "$path1";
$sql = "INSERT INTO uploads (image,house,image1,build) VALUES ('$actualpath','$house','$actualpath1','$build')";
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";
}
?>
这是错误..
Logcat
02-17 17:28:33.261: E/AndroidRuntime(14710): FATAL EXCEPTION: main
02-17 17:28:33.261: E/AndroidRuntime(14710): java.lang.NullPointerException
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.example.test.MainActivity.getStringImage1(MainActivity.java:118)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.example.test.MainActivity.uploadImage(MainActivity.java:129)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.example.test.MainActivity.onClick(MainActivity.java:168)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.view.View.performClick(View.java:4191)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.view.View$PerformClick.run(View.java:17229)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.os.Handler.handleCallback(Handler.java:615)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.os.Handler.dispatchMessage(Handler.java:92)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.os.Looper.loop(Looper.java:137)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.app.ActivityThread.main(ActivityThread.java:4960)
02-17 17:28:33.261: E/AndroidRuntime(14710): at java.lang.reflect.Method.invokeNative(Native Method)
02-17 17:28:33.261: E/AndroidRuntime(14710): at java.lang.reflect.Method.invoke(Method.java:511)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-17 17:28:33.261: E/AndroidRuntime(14710): at dalvik.system.NativeStart.main(Native Method)
当你打电话给public void uploadImage()
检查
String image = null;
String image1 = null;
if(bitmap != null)
image = getStringImage(bitmap);
if(bitmap1 != null)
image1 = getStringImage1(bitmap1);
也检查
if(image != null)
param.put(KEY_IMAGE,image);
if(image1 != null)
param.put(KEY_IMAGE1,image1);
String result = rh.sendPostRequest(UPLOAD_URL, param);
然后也在 php 中检查是否
KEY_IMAGE
和
KEY_IMAGE1
exists然后做任何你想做的事,否则php会抛出未定义索引的错误。
您正在选择一张图片并在 uploadimage 方法中上传两张...
只需使用下面的代码即可。
String image1 = "";
if(bitmap1!=null)
image1 = getStringImage1(bitmap1);
在我的代码中,我有两个图像和两个 edittext 字段要发送到数据库,使用 php file.Here 在我的代码中,我可以插入 2 个图像和 edittext 字段,而无需任何问题。
现在我的问题是,当用户输入两个编辑文本字段并且 select 只插入一张图像时,它会抛出 NullPointerException
。使用此代码,我必须强制性地 select 2 张图像。 .我怎样才能让那个成为可选的?我的意思是用户可以 select one/two 基于他的 requirement.But 的图像,如果我 select 只有一个图像,它会抛出空指针 exception.please 帮帮我..!!
MainActivity.java
package com.example.test;
import android.app.Activity;
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 Activity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
private Button buttonChoose1;
private EditText edithouse;
private EditText editbuild;
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 = "house";
public static final String KEY_TEXT1 = "build";
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.save);
buttonChoose = (Button) findViewById(R.id.choose);
buttonChoose1 = (Button) findViewById(R.id.choose1);
edithouse = (EditText) findViewById(R.id.houseno);
editbuild = (EditText) findViewById(R.id.buildno);
imageView = (ImageView) findViewById(R.id.imageViews);
imageView1 = (ImageView) findViewById(R.id.imageViews1);
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 house = edithouse.getText().toString().trim();
final String build = editbuild.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,house);
param.put(KEY_TEXT1,build);
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
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$house = $_POST['house '];
$image1 = $_POST['image1'];
$build = $_POST['build '];
require_once('dbConnect.php');
$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/".uniqid().".png";
$path1 = "uploads/".uniqid().".png";
$actualpath = "$path";
$actualpath1 = "$path1";
$sql = "INSERT INTO uploads (image,house,image1,build) VALUES ('$actualpath','$house','$actualpath1','$build')";
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";
}
?>
这是错误.. Logcat
02-17 17:28:33.261: E/AndroidRuntime(14710): FATAL EXCEPTION: main
02-17 17:28:33.261: E/AndroidRuntime(14710): java.lang.NullPointerException
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.example.test.MainActivity.getStringImage1(MainActivity.java:118)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.example.test.MainActivity.uploadImage(MainActivity.java:129)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.example.test.MainActivity.onClick(MainActivity.java:168)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.view.View.performClick(View.java:4191)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.view.View$PerformClick.run(View.java:17229)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.os.Handler.handleCallback(Handler.java:615)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.os.Handler.dispatchMessage(Handler.java:92)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.os.Looper.loop(Looper.java:137)
02-17 17:28:33.261: E/AndroidRuntime(14710): at android.app.ActivityThread.main(ActivityThread.java:4960)
02-17 17:28:33.261: E/AndroidRuntime(14710): at java.lang.reflect.Method.invokeNative(Native Method)
02-17 17:28:33.261: E/AndroidRuntime(14710): at java.lang.reflect.Method.invoke(Method.java:511)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-17 17:28:33.261: E/AndroidRuntime(14710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-17 17:28:33.261: E/AndroidRuntime(14710): at dalvik.system.NativeStart.main(Native Method)
当你打电话给public void uploadImage()
检查
String image = null;
String image1 = null;
if(bitmap != null)
image = getStringImage(bitmap);
if(bitmap1 != null)
image1 = getStringImage1(bitmap1);
也检查
if(image != null)
param.put(KEY_IMAGE,image);
if(image1 != null)
param.put(KEY_IMAGE1,image1);
String result = rh.sendPostRequest(UPLOAD_URL, param);
然后也在 php 中检查是否
KEY_IMAGE
和
KEY_IMAGE1
exists然后做任何你想做的事,否则php会抛出未定义索引的错误。
您正在选择一张图片并在 uploadimage 方法中上传两张...
只需使用下面的代码即可。
String image1 = "";
if(bitmap1!=null)
image1 = getStringImage1(bitmap1);